package com.cusc.nirvana.user.rnr.fp.dao.handler;

import com.cusc.nirvana.user.util.crypt.CryptKeyUtil;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedTypes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

/**
 * 拦截 JavaType 为 #{@link EncryptData} 的 SQL
 * <p>
 * 注意：
 * </p>
 * <p>
 * 1. 加密时字段只过滤 null值，明文不做任何处理直接加密
 * </p>
 * <p>
 * 2. fail fast 模式，当加/解密失败时，立即抛出异常
 * </p>
 *
 * @author xufeng @ 2017年8月31日
 */
@MappedTypes(EncryptData.class)
public class EncryptDataTypeHandler extends BaseTypeHandler<String> {

    private static final Logger logger = LoggerFactory.getLogger(EncryptDataTypeHandler.class);

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType)
            throws SQLException {
        ps.setString(i, CryptKeyUtil.encryptToBase64(parameter));
    }

    @Override
    public String getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return CryptKeyUtil.decryptByBase64(rs.getString(columnName));
    }

    @Override
    public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return CryptKeyUtil.decryptByBase64(rs.getString(columnIndex));
    }

    @Override
    public String getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return CryptKeyUtil.decryptByBase64(cs.getString(columnIndex));
    }
}
