package com.cf.imes.framework.mybatis.core.type;

import com.cf.imes.framework.common.util.json.JsonUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.StringTypeHandler;

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

/**
 * mb自定义压缩字符串类型转换器
 *
 * @author Gqr
 * @since 2024/7/10 16:05
 */
public class CompressStringTypeHandler extends StringTypeHandler {
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType)
            throws SQLException {
        String compressString = null;
        if (StringUtils.isNotEmpty(parameter)) {
            compressString = JsonUtils.zipString(parameter);
        }
        ps.setString(i, compressString);
    }

    @Override
    public String getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String compressedString = rs.getString(columnName);
        return unzipString(compressedString);
    }

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

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

    private String unzipString(String compressedString) {
        if (StringUtils.isNotEmpty(compressedString)) {
            return JsonUtils.unzipString(compressedString);
        } else {
            return null;
        }
    }
}
