package lingtao.net.handler;

import com.alibaba.fastjson.JSON;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;

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

public class MapToVarcharTypeHandler implements TypeHandler<Map<String, String>> {
    @Override
    public void setParameter(PreparedStatement ps, int i, Map<String, String> parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(i, JSON.toJSONString(parameter));
    }

    @Override
    public Map<String, String> getResult(ResultSet rs, String columnName) throws SQLException {
        String resultString = rs.getString(columnName);
        if (StringUtils.isEmpty(resultString)) {
            return JSON.parseObject(resultString, Map.class);
        }
        return null;
    }

    @Override
    public Map<String, String> getResult(ResultSet rs, int columnIndex) throws SQLException {
        String resultString = rs.getString(columnIndex);
        if (StringUtils.isEmpty(resultString)) {
            return JSON.parseObject(resultString, Map.class);
        }
        return null;
    }

    @Override
    public Map<String, String> getResult(CallableStatement cs, int columnIndex) throws SQLException {
        String resultString = cs.getString(columnIndex);
        if (StringUtils.isEmpty(resultString)) {
            return JSON.parseObject(resultString, Map.class);
        }
        return null;
    }
}
