package com.seer.teach.mall.handler;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.seer.teach.mall.entity.GoodsSpecificationEntity;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.springframework.util.StringUtils;

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

@Slf4j
public class GoodsSpecAttributesTypeHandler extends BaseTypeHandler<List<GoodsSpecificationEntity.Attribute>> {
    private static final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, List<GoodsSpecificationEntity.Attribute> parameter, JdbcType jdbcType) throws SQLException {
        try {
            ps.setString(i, objectMapper.writeValueAsString(parameter));
        } catch (JsonProcessingException e) {
            log.error(e.getMessage(), e);
        }
    }

    @Override
    public List<GoodsSpecificationEntity.Attribute> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String json = rs.getString(columnName);
        try {
            if(StringUtils.hasText( json)){
                return objectMapper.readValue(json, new TypeReference<List<GoodsSpecificationEntity.Attribute>>(){});
            }
            return null;
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<GoodsSpecificationEntity.Attribute> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String json = rs.getString(columnIndex);
        try {
            if(StringUtils.hasText( json)){
                return objectMapper.readValue(json, new TypeReference<List<GoodsSpecificationEntity.Attribute>>(){});
            }
            return null;
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<GoodsSpecificationEntity.Attribute> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String json = cs.getString(columnIndex);
        try {
            if(StringUtils.hasText( json)){
                return objectMapper.readValue(json, new TypeReference<List<GoodsSpecificationEntity.Attribute>>(){});
            }
            return null;
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }


}