package com.Modules.etl.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.*;

@MappedTypes(byte[][].class)
@MappedJdbcTypes(JdbcType.ARRAY)
public class ArrayByteTypeHandler extends BaseTypeHandler<byte[][]> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, byte[][] parameter, JdbcType jdbcType) throws SQLException {
        Array array = ps.getConnection().createArrayOf("bytea", parameter);
        ps.setArray(i, array);
    }

    @Override
    public byte[][] getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return getArray(rs.getArray(columnName));
    }

    @Override
    public byte[][] getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return getArray(rs.getArray(columnIndex));
    }

    @Override
    public byte[][] getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return getArray(cs.getArray(columnIndex));
    }

    private byte[][] getArray(Array array) throws SQLException {
        if (array != null) {
            Object[] objArray = (Object[]) array.getArray();
            byte[][] result = new byte[objArray.length][];
            for (int i = 0; i < objArray.length; i++) {
                result[i] = (byte[]) objArray[i];
            }
            return result;
        }
        return null;
    }
}