package com.qaup.collision.dataprocessing.service;

import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.opengis.referencing.operation.MathTransform;
import org.geotools.geometry.jts.JTS;
import org.geotools.referencing.CRS;
import org.locationtech.jts.geom.Coordinate;


public class AirportCoordinateSystem {
    private final CoordinateReferenceSystem sourceCRS;
    private final CoordinateReferenceSystem targetCRS;
    private final MathTransform transform;
    // 本地坐标系原点
    private final double[] origin;


    public AirportCoordinateSystem(double centerLon, double centerLat) throws Exception {
        this.sourceCRS = CRS.decode("EPSG:4326",true);
        String utmCode = calculateUtmZone(centerLon, centerLat);
        this.targetCRS = CRS.decode(utmCode);

        // 创建转换器并计算原点
        this.transform = CRS.findMathTransform(sourceCRS, targetCRS);
        this.origin = transformCoordinate(centerLon, centerLat);
    }

    // 转换单个坐标（返回相对于原点的坐标）
    public double[] convertToLocal(double lon, double lat) throws Exception {
        double[] utm = transformCoordinate(lon, lat);
        return new double[]{
            utm[0] - origin[0],
            utm[1] - origin[1]
        };
    }

    private double[] transformCoordinate(double lon, double lat) throws Exception {
        Coordinate source = new Coordinate(lon, lat);
        Coordinate target = new Coordinate();
        JTS.transform(source, target, transform);
        return new double[]{target.x, target.y};
    }

    public static String calculateUtmZone(double lon, double lat) {
        int zone = (int) Math.floor((lon + 180) / 6) + 1;
        // 北半球编码
        return "EPSG:326" + (zone < 10 ? "0" : "") + zone;
    }
}
