package com.nuliji.tools.mybatis.handler;

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

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@MappedTypes(Integer[].class)
@MappedJdbcTypes({JdbcType.LONGVARCHAR, JdbcType.VARCHAR})
public class IntegerArrayHandler extends BaseTypeHandler<Integer[]> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Integer[] parameter, JdbcType jdbcType) throws SQLException {
        List<String> list = new ArrayList<>();
        for (Integer item : parameter) {
            list.add(String.valueOf(item));
        }
        ps.setString(i, String.join(",", list));
    }

    @Override
    public Integer[] getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String str = rs.getString(columnName);
        if (rs.wasNull())
            return null;

        return Arrays.stream(str.split(",")).map(Integer::valueOf).toArray(Integer[]::new);
    }

    @Override
    public Integer[] getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String str = rs.getString(columnIndex);
        if (rs.wasNull())
            return null;

        return Arrays.stream(str.split(",")).map(Integer::valueOf).toArray(Integer[]::new);
    }

    @Override
    public Integer[] getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String str = cs.getString(columnIndex);
        if (cs.wasNull())
            return null;

        return Arrays.stream(str.split(",")).map(Integer::valueOf).toArray(Integer[]::new);
    }
}

