package com.changhu.support.mybatisplus.handler.global.geo;

import cn.hutool.core.util.ClassUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.changhu.common.utils.GeometryUtil;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.locationtech.jts.geom.Point;

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

/**
 * author: luozhun
 * desc: PointTypeHandler
 * createTime: 2023/8/26 13:17
 */
@MappedJdbcTypes(JdbcType.VARCHAR)
@MappedTypes(Point.class)
public class PointTypeHandler extends AbstractGeometryTypeHandler<Point> {

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, Point point, JdbcType jdbcType) throws SQLException {
        preparedStatement.setString(i, point.toText());
    }

    @Override
    public Point getNullableResult(ResultSet resultSet, String s) throws SQLException {
        return createPoint(resultSet.getString(s), resultSet.getBytes(s));
    }

    @Override
    public Point getNullableResult(ResultSet resultSet, int i) throws SQLException {
        return createPoint(resultSet.getString(i), resultSet.getBytes(i));
    }

    @Override
    public Point getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        return createPoint(callableStatement.getString(i), callableStatement.getBytes(i));
    }

    public Point createPoint(String pointStr, byte[] pointBytes) {
        if (JSONUtil.isTypeJSON(pointStr)) {
            return GeometryUtil.createGeometryFromGeoJson(pointStr, Point.class);
        }
        if (StrUtil.startWithIgnoreCase(pointStr, ClassUtil.getClassName(Point.class, true))) {
            return GeometryUtil.createGeometryFromWkt(pointStr, Point.class);
        }
        return GeometryUtil.createPoint(pointBytes);
    }
}
