package com.sonic.daosupport.mysql.typehandler;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Set;

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 com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.google.common.collect.ImmutableSet;

/**
 * @author code
 */
@MappedTypes({Set.class})
@MappedJdbcTypes(JdbcType.VARCHAR)
public abstract class BaseSetTypeHandler<T> extends BaseTypeHandler<Set<T>> {

    private Class<T> type = getGenericType();

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i,
                                    Set<T> list, JdbcType jdbcType) throws SQLException {
        preparedStatement.setString(i, JSONArray.toJSONString(list, SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteNullListAsEmpty, SerializerFeature.WriteNullStringAsEmpty));
    }

    @Override
    public Set<T> getNullableResult(ResultSet resultSet, String s) throws SQLException {
        return ImmutableSet.copyOf(JSONArray.parseArray(resultSet.getString(s), type));
    }

    @Override
    public Set<T> getNullableResult(ResultSet resultSet, int i) throws SQLException {
        return ImmutableSet.copyOf(JSONArray.parseArray(resultSet.getString(i), type));
    }

    @Override
    public Set<T> getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        return ImmutableSet.copyOf(JSONArray.parseArray(callableStatement.getString(i), type));
    }

    private Class<T> getGenericType() {
        Type t = getClass().getGenericSuperclass();
        Type[] params = ((ParameterizedType) t).getActualTypeArguments();
        return (Class<T>) params[0];
    }
}
