package com.fs.watch.handler;

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

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

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

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

    @Override
    public List<Integer> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        Array array = rs.getArray(columnName);
        if (array == null) {
            return null;
        }
        // 使用 int[] 而不是 Integer[]
        int[] intArray = (int[]) array.getArray();
        List<Integer> resultList = new ArrayList<>();
        for (int value : intArray) {
            resultList.add(value);
        }
        return resultList;
    }

    @Override
    public List<Integer> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        Array array = rs.getArray(columnIndex);
        if (array == null) {
            return null;
        }
        int[] intArray = (int[]) array.getArray();
        List<Integer> resultList = new ArrayList<>();
        for (int value : intArray) {
            resultList.add(value);
        }
        return resultList;
    }

    @Override
    public List<Integer> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        Array array = cs.getArray(columnIndex);
        if (array == null) {
            return null;
        }
        int[] intArray = (int[]) array.getArray();
        List<Integer> resultList = new ArrayList<>();
        for (int value : intArray) {
            resultList.add(value);
        }
        return resultList;
    }
}
