package com.sonic.daosupport.mysql.typehandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collections;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;

import com.google.common.base.Splitter;
import com.google.common.collect.Sets;

/**
 * 1. 用于将数据库中的, 逗号分割的String, 转换为Set.
 * 2. 存储时将Set直接存String, 多个使用逗号分割
 * @author code
 */
@MappedJdbcTypes({JdbcType.VARCHAR})
public class SetCommaTypeHandler extends BaseTypeHandler<Set<String>> {

    private static final String DELIMITER = ",";

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Set<String> parameter, JdbcType jdbcType) throws SQLException {
        String value = Sets.newLinkedHashSet(Optional.ofNullable(parameter).orElse(Collections.emptySet()))
                .stream()
                .collect(Collectors.joining(DELIMITER));

        ps.setString(i, value);
    }

    @Override
    public Set<String> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return getSet(rs.getString(columnName));
    }

    @Override
    public Set<String> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return getSet(rs.getString(columnIndex));
    }

    @Override
    public Set<String> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return getSet(cs.getString(columnIndex));
    }

    private Set<String> getSet(String dbValue) {
        return Splitter.on(",")
                .omitEmptyStrings()
                .trimResults()
                .splitToList(Optional.of(dbValue).orElse(StringUtils.EMPTY))
                .stream()
                .collect(Collectors.toSet());
    }
}
