package com.zhiqiyun.open.core.typeHandler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import lombok.extern.slf4j.Slf4j;
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;

@Slf4j
@MappedTypes({Object.class})
@MappedJdbcTypes({JdbcType.VARCHAR})
public class FastjsonTypeHandler<E> extends BaseTypeHandler<E> {

    private E parse(String jsonValue) {
        return jsonValue != null && jsonValue.length() != 0 ? JSON.parseObject(jsonValue, new TypeReference<E>() {
        }) : null;
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, E parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(i, JSON.toJSONString(parameter));
    }


    @Override
    public E getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return this.parse(rs.getString(columnName));
    }

    @Override
    public E getNullableResult(ResultSet rs, int i) throws SQLException {
        return this.parse(rs.getString(i));
    }

    @Override
    public E getNullableResult(CallableStatement cs, int i) throws SQLException {
        return this.parse(cs.getString(i));
    }
}
