package com.fs.watch.handler;

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

import java.sql.*;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class IntegerArrayTypeHandler extends BaseTypeHandler<List<Integer>> {

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

    @Override
    public List<Integer> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        Array array = rs.getArray(columnName);
        if (array == null) {
            return null;
        }
        Integer[] result = (Integer[]) array.getArray();
        return Arrays.stream(result).collect(Collectors.toList());
    }

    @Override
    public List<Integer> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        Array array = rs.getArray(columnIndex);
        if (array == null) {
            return null;
        }
        Integer[] result = (Integer[]) array.getArray();
        return Arrays.stream(result).collect(Collectors.toList());
    }

    @Override
    public List<Integer> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        Array array = cs.getArray(columnIndex);
        if (array == null) {
            return null;
        }
        Integer[] result = (Integer[]) array.getArray();
        return Arrays.stream(result).collect(Collectors.toList());
    }
}
