package com.fs.watch.handler;

import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;

import java.sql.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class FloatArrayTypeHandler implements TypeHandler<List<Float>> {

    @Override
    public void setParameter(PreparedStatement ps, int i, List<Float> parameter, JdbcType jdbcType) throws SQLException {
        if (parameter == null) {
            ps.setNull(i, Types.ARRAY);
        } else {
            Float[] array = parameter.toArray(new Float[0]);
            ps.setArray(i, ps.getConnection().createArrayOf("FLOAT8", array));
        }
    }

    @Override
    public List<Float> getResult(ResultSet rs, String columnName) throws SQLException {
        Array array = rs.getArray(columnName);
        if (array == null) {
            return null;
        }
        Object objArray = array.getArray();
        return convertToList(objArray);
    }

    @Override
    public List<Float> getResult(ResultSet rs, int columnIndex) throws SQLException {
        Array array = rs.getArray(columnIndex);
        if (array == null) {
            return null;
        }
        Object objArray = array.getArray();
        return convertToList(objArray);
    }

    @Override
    public List<Float> getResult(CallableStatement cs, int columnIndex) throws SQLException {
        Array array = cs.getArray(columnIndex);
        if (array == null) {
            return null;
        }
        Object objArray = array.getArray();
        return convertToList(objArray);
    }

    private List<Float> convertToList(Object objArray) {
        List<Float> list = new ArrayList<>();
        if (objArray instanceof float[]) {
            for (float f : (float[]) objArray) {
                list.add(f);
            }
        } else if (objArray instanceof Float[]) {
            list.addAll(Arrays.asList((Float[]) objArray));
        }
        return list;
    }
}
