package com.nokia.common.mybatis;

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

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 用于在mybatis中将java类型转化成json字符串存入数据库和从数据库读取json数据转化为java类型
 * 无法转化集合类型
 */
public class JsonTypeHandler<T extends Object> extends BaseTypeHandler<T> {

    private static final ObjectMapper MAPPER = new ObjectMapper();
    private Class<T> clz;

    public JsonTypeHandler(Class<T> clz) {
        this.clz = clz;
    }

    @Override
    public T getNullableResult(ResultSet resultSet, String columnName) throws SQLException {
        if (columnName == null || columnName.isEmpty()) {
            return null;
        }
        return (T) toObject(resultSet.getString(columnName), clz);
    }

    @Override
    public T getNullableResult(ResultSet resultSet, int columnIndex) throws SQLException {
        return (T) toObject(resultSet.getString(columnIndex), clz);
    }

    @Override
    public T getNullableResult(CallableStatement callableStatement, int columnIndex) throws SQLException {
        return (T) toObject(callableStatement.getString(columnIndex), clz);
    }

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int columnIndex, T parameter,
            JdbcType jdbcType)
            throws SQLException {
        preparedStatement.setString(columnIndex, toJson(parameter));
    }

    private String toJson(T parameter) {
        try {
            return MAPPER.writeValueAsString(parameter);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    private T toObject(String content, Class<T> clz) {
        if (content == null || content.isEmpty()) {
            return null;
        }
        try {
            return (T) MAPPER.readValue(content, clz);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

}
