package com.fs.watch.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.io.IOException;
import java.sql.*;
import java.util.List;

public class ShortListTypeHandler extends BaseTypeHandler<List<Short>> {

    private static final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, List<Short> parameter, JdbcType jdbcType) throws SQLException {
        try {
            String json = objectMapper.writeValueAsString(parameter);
            ps.setObject(i, json, Types.OTHER);
        } catch (IOException e) {
            throw new SQLException("Failed to convert Short list to JSON", e);
        }
    }

    @Override
    public List<Short> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String json = rs.getString(columnName);
        if (json != null) {
            try {
                return objectMapper.readValue(json, objectMapper.getTypeFactory().constructCollectionType(List.class, Short.class));
            } catch (IOException e) {
                throw new SQLException("Failed to convert JSON to Short list", e);
            }
        }
        return null;
    }

    @Override
    public List<Short> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String json = rs.getString(columnIndex);
        if (json != null) {
            try {
                return objectMapper.readValue(json, objectMapper.getTypeFactory().constructCollectionType(List.class, Short.class));
            } catch (IOException e) {
                throw new SQLException("Failed to convert JSON to Short list", e);
            }
        }
        return null;
    }

    @Override
    public List<Short> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String json = cs.getString(columnIndex);
        if (json != null) {
            try {
                return objectMapper.readValue(json, objectMapper.getTypeFactory().constructCollectionType(List.class, Short.class));
            } catch (IOException e) {
                throw new SQLException("Failed to convert JSON to Short list", e);
            }
        }
        return null;
    }
}
