package com.bcxin.tenant.open.domains.typeHandlers;

import com.bcxin.tenant.open.infrastructures.components.JsonProvider;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedTypes;

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

@MappedTypes({Collection.class})
public class StationTypeHandler  extends BaseTypeHandler<Collection> {

    private final JsonProvider jsonProvider;

    public StationTypeHandler() {
        this.jsonProvider = new JsonProvider.DefaultJsonProvider();
    }

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, Collection collection, JdbcType jdbcType) throws SQLException {
        preparedStatement.setBytes(i, this.jsonProvider.getJson(collection).getBytes());
    }

    @Override
    public Collection getNullableResult(ResultSet resultSet, String columnName) throws SQLException {
        return this.jsonProvider.toObject(Collection.class, resultSet.getString(columnName));
    }

    @Override
    public Collection getNullableResult(ResultSet resultSet, int columnIndex) throws SQLException {
        return jsonProvider.toObject(Collection.class, resultSet.getString(columnIndex));
    }

    @Override
    public Collection getNullableResult(CallableStatement callableStatement, int columnIndex) throws SQLException {
        return jsonProvider.toObject(Collection.class, callableStatement.getString(columnIndex));
    }
}
