package com.siwei.spatial.service.maths.impl;

import com.siwei.common.core.exception.ServiceException;
import com.siwei.spatial.service.maths.ISpatialMathsService;
import org.locationtech.jts.geom.Envelope;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.GeometryFactory;
import org.locationtech.jts.io.ParseException;
import org.locationtech.jts.io.WKTReader;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class SpatialMathsServiceImpl implements ISpatialMathsService {
    @Override
    public String getGeomEnvelope(List<String> geoms) {
        if (geoms == null || geoms.isEmpty()) {
            throw new ServiceException("Input WKT cannot be empty");
        }
        try {
            List<Geometry> geometryList = new ArrayList<>();
            for (String geom : geoms) {
                geometryList.add(parse(geom));
            }
            Geometry[] geometries = geometryList.toArray(new Geometry[0]);
            Geometry combinedEnv = getCombinedEnvelopeWithSRID(geometries);
            if (combinedEnv.getSRID() == 0) {
                return combinedEnv.toText();
            } else {
                return "SRID=" + combinedEnv.getSRID() + ";" + combinedEnv.toText();
            }
//            System.out.println("Combined Envelope (SRID=" + combinedEnv.getSRID() + "): " + combinedEnv.toText());
        } catch (ParseException e) {
            throw new ServiceException(e.getMessage());
        }
    }

    private Geometry parse(String input) throws ParseException {
        // 处理空值
        if (input == null || input.trim().isEmpty()) {
            throw new ParseException("Input WKT cannot be empty");
        }

        String wkt = input.trim();
        int srid = 0;
        String wkt_query = wkt.toLowerCase();
        // 检查并提取SRID
        if (wkt_query.startsWith("srid=") && wkt.indexOf(';') > 5) {
            try {
                srid = Integer.parseInt(wkt.substring(5, wkt.indexOf(';')));
                wkt = wkt.substring(wkt.indexOf(';') + 1);
            } catch (NumberFormatException e) {
                throw new ParseException("Invalid SRID format");
            }
        }

        // 解析几何对象
        Geometry geom = new WKTReader().read(wkt);
        geom.setSRID(srid);
        return geom;
    }

    public Geometry getCombinedEnvelopeWithSRID(Geometry[] geometries) {
        if (geometries == null || geometries.length == 0) {
            return null;
        }

        int srid = geometries[0].getSRID();
        for (Geometry geom : geometries) {
            if (geom.getSRID() != srid) {
                throw new IllegalArgumentException("所有几何体必须具有相同的 SRID");
            }
        }

        Envelope combinedEnvelope = new Envelope();
        for (Geometry geom : geometries) {
            combinedEnvelope.expandToInclude(geom.getEnvelopeInternal());
        }

        GeometryFactory factory = geometries[0].getFactory();
        Geometry result = factory.toGeometry(combinedEnvelope);
        result.setSRID(srid);
        return result;
    }
}
