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 ArrayTypeHandler extends BaseTypeHandler<List<Integer>> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, List<Integer> parameter, JdbcType jdbcType) throws SQLException {
        // 将 List<Integer> 转换为 SQL 的数组类型
        Connection connection = ps.getConnection();
        Array array = connection.createArrayOf("Int16", parameter.toArray());
        ps.setArray(i, array);
    }

    @Override
    public List<Integer> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        // 将 SQL 的数组类型转换为 List<Integer>
        Array array = rs.getArray(columnName);
        if (array == null) {
            return null;
        }
        Integer[] integers = (Integer[]) array.getArray();
        List<Integer> list = new ArrayList<>();
        for (Integer i : integers) {
            list.add(i);
        }
        return list;
    }

    @Override
    public List<Integer> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        // 同样的转换逻辑，但基于列索引
        Array array = rs.getArray(columnIndex);
        if (array == null) {
            return null;
        }
        Integer[] integers = (Integer[]) array.getArray();
        List<Integer> list = new ArrayList<>();
        for (Integer i : integers) {
            list.add(i);
        }
        return list;
    }

    @Override
    public List<Integer> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        // 同样的转换逻辑，用于存储过程的返回值
        Array array = cs.getArray(columnIndex);
        if (array == null) {
            return null;
        }
        Integer[] integers = (Integer[]) array.getArray();
        List<Integer> list = new ArrayList<>();
        for (Integer i : integers) {
            list.add(i);
        }
        return list;
    }
}
