package ru.nbch.credit_tracker.config.datasource.handlers;

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

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

@MappedTypes(BigInteger.class)
public class BigIntegerTypeHandler extends BaseTypeHandler<BigInteger> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, BigInteger parameter, JdbcType jdbcType) throws SQLException {
        ps.setLong(i, parameter.longValue());
    }

    @Override
    public BigInteger getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String value = rs.getString(columnName);
        if (rs.wasNull()) {
            return null;
        } else {
            try {
                return BigInteger.valueOf(Long.parseLong(value.trim()));
            } catch (NumberFormatException e) {
                return null;
            }
        }
    }

    @Override
    public BigInteger getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String value = rs.getString(columnIndex);
        if (rs.wasNull()) {
            return null;
        } else {
            try {
                return BigInteger.valueOf(Long.parseLong(value.trim()));
            } catch (NumberFormatException e) {
                return null;
            }
        }
    }

    @Override
    public BigInteger getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String value = cs.getString(columnIndex);
        if (cs.wasNull()) {
            return null;
        } else {
            try {
                return BigInteger.valueOf(Long.parseLong(value.trim()));
            } catch (NumberFormatException e) {
                return null;
            }
        }
    }
}
