package com.ruoyi.ibs.grid.util;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedTypes;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.io.ParseException;
import org.locationtech.jts.io.WKTReader;
import org.locationtech.jts.io.WKTWriter;

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

@MappedTypes(Geometry.class)
public class GeometryTypeHandler extends BaseTypeHandler<Geometry> {

    private final WKTReader reader = new WKTReader();
    private final WKTWriter writer = new WKTWriter();

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Geometry parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(i, writer.write(parameter));
    }

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

    @Override
    public Geometry getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return toGeometry(rs.getString(columnIndex));
    }

    @Override
    public Geometry getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return toGeometry(cs.getString(columnIndex));
    }

    private Geometry toGeometry(String wkt) throws SQLException {
        try {
            return wkt == null ? null : reader.read(wkt);
        } catch (ParseException e) {
            System.out.println("--------------------->error:" + wkt);
            throw new SQLException("Error converting WKT to Geometry", e);
        }
    }
}