package cn.quant.andy.jpa.mybatis.type;

import cn.quant.andy.jpa.model.ImportMapSchema;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
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.text.SimpleDateFormat;
import java.util.List;

/**
 * Created by Administrator on 2021/7/17 0017.
 */
@MappedJdbcTypes(JdbcType.LONGVARCHAR)
@MappedTypes(List.class)
public class SchemaListTypeHandler extends BaseTypeHandler<List<ImportMapSchema>> {

    private final static ObjectMapper mapper = new ObjectMapper();

    static {
        mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    }

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, List<ImportMapSchema> importDataSchema, JdbcType jdbcType) throws SQLException {

    }

    @Override
    public List getNullableResult(ResultSet resultSet, String s) throws SQLException {
        return getNullableResult(resultSet.getString(s));
    }

    @Override
    public List<ImportMapSchema> getNullableResult(ResultSet resultSet, int i) throws SQLException {
        return getNullableResult(resultSet.getString(i));
    }

    @Override
    public List<ImportMapSchema> getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        return null;
    }

    public List<ImportMapSchema> getNullableResult(String val) {
        try {
            if (val.charAt(0) == '[') {
                if (val.charAt(Math.max(val.length() - 1, 0)) == ']') {
                    return mapper.readValue(val, new TypeReference<List<ImportMapSchema>>() {});
                }
            }
            return null;
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }
}
