/*
 * RiskScape™ Copyright New Zealand Institute for Earth Science Limited
 * (Earth Sciences New Zealand) is distributed for research purposes only
 * under the terms of AGPLv3.
 *
 * RiskScape™ Copyright 2026 New Zealand Institute for Earth Science
 * Limited (Earth Sciences New Zealand). All rights reserved. Source code
 * available under the AGPLv3.
 * 
 * This program is free software: you can redistribute it and/or modify it under
 *  the terms of the GNU Affero General Public License as published by the Free
 *  Software Foundation, either version 3 of the License, or (at your option) any
 *  later version.
 * 
 * This program is distributed for RESEARCH PURPOSES ONLY, in the hope that it will
 * be useful for research and education initiatives.
 * 
 * If you are not a researcher, or you are a researcher who wishes to use this
 * program on terms other than AGPLv3 (including those who wish to restrict the
 * distribution of any source code created using this program), please contact:
 * https://riskscape.org.nz
 * 
 * This program is distributed WITHOUT ANY WARRANTY; without even the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Affero General Public License for more details.  You should have received a copy
 * of the GNU Affero General Public License along with this program.  If not, see
 * <http://www.gnu.org/licenses/>.
 * 
 * By way of summary only, under the AGPLv3:
 *     • Permissions of this strongest copyleft license are conditioned
 *       on making available complete source code of licensed works and
 *       modifications, which include larger works using a licensed work,
 *       under the same license.
 *     • Copyright and license notices must be preserved.
 *     • Contributors provide an express grant of patent rights.
 *     • When a modified version is used to provide a service over a
 *       network, the complete source code of the modified version must be made
 *       available.
 */
package nz.org.riskscape.engine.gt;

import java.util.Arrays;

import org.geotools.api.referencing.crs.CoordinateReferenceSystem;
import org.geotools.geometry.jts.CompoundCurve;
import org.geotools.geometry.jts.CurvePolygon;
import org.geotools.geometry.jts.MultiCurve;
import org.geotools.geometry.jts.MultiSurface;
import org.geotools.geometry.jts.ReferencedEnvelope;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.CoordinateSequence;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.GeometryCollection;
import org.locationtech.jts.geom.GeometryFactory;
import org.locationtech.jts.geom.LineString;
import org.locationtech.jts.geom.LinearRing;
import org.locationtech.jts.geom.MultiLineString;
import org.locationtech.jts.geom.MultiPoint;
import org.locationtech.jts.geom.MultiPolygon;
import org.locationtech.jts.geom.Point;
import org.locationtech.jts.geom.Polygon;
import org.locationtech.jts.io.WKTReader;

import nz.org.riskscape.engine.CrsHelper;
import nz.org.riskscape.engine.SRIDSet;

/**
 * Has methods for constructing geometries with less ceremony than JTS usually requires, taking care to make SRIDs
 * match up with an SRIDSet
 */
public interface GeometryHelper extends CrsHelper {

  /*
   * Arbitrary valid locations within NZTM coordinate space
   */
  int NZTM_ORIGIN_NORTHING = 5500000;
  int NZTM_ORIGIN_EASTING = 1800000;

  /**
   * @return an nztm helper where coordinates are always created with a shift around a realistic origin, so that
   * reprojected geometries end up in realistic locations.
   */
  static GeometryHelper nzTransverseMercatorWithOriginShift(SRIDSet sridSet) {
    return create(sridSet, SRIDSet.EPSG2193_NZTM, new Coordinate(NZTM_ORIGIN_NORTHING, NZTM_ORIGIN_EASTING));
  }

  /**
   * Same as {@link #nzTransverseMercator()} but with force xy.
   */
  static GeometryHelper nzTransverseMercatorXYWithOriginShift(SRIDSet sridSet) {
    return create(sridSet, SRIDSet.epsgToCrsWithForceXY("EPSG:2193"),
        new Coordinate(NZTM_ORIGIN_EASTING, NZTM_ORIGIN_NORTHING));
  }
  /**
   * @return an nztm helper, but without shifting coordinates by a "realistic" origin
   */
  static GeometryHelper nzTransverseMercator(SRIDSet sridSet) {
    return create(sridSet, SRIDSet.EPSG2193_NZTM);
  }

  /**
   * Geometry helper using lat/lon (y/x). Caution should be taken with this CRS because it has previously
   * been defined as lon/lat and many other software packages still treat it that way.
   */
  static GeometryHelper latLong(SRIDSet sridSet) {
    return create(sridSet, SRIDSet.EPSG4326_LATLON);
  }

  /**
   * WGS84 Long/Lat (x/y) helper
   */
  static GeometryHelper longLat(SRIDSet sridSet) {
    return create(sridSet, SRIDSet.EPSG4326_LONLAT);
  }

  /**
   * Old-School NZ Map Grid helper, shifted to a location with NZ somewhere so that reprojections are valid.
   * You probably want {@link #nzTransverseMercator()}.
   */
  static GeometryHelper nzMapGridWithOriginShift(SRIDSet sridSet) {
    return create(sridSet, SRIDSet.EPSG_27200_NZMG, new Coordinate(2700000, 6000000));
  }

  /**
   * NZGD2000 is a lat/long projection with a longitude range from 0-360
   */
  static GeometryHelper nzGrid(SRIDSet sridSet) {
    return create(sridSet, SRIDSet.epsgToCrs("EPSG:4167"));
  }
  /**
   * Obscure non-metric grid for North America using US Feet instead of metres.
   */
  static GeometryHelper newYorkFoot(SRIDSet sridSet) {
    return create(sridSet, SRIDSet.epsgToCrs("EPSG:2263"));
  }

  static GeometryHelper create(SRIDSet sridSet, CoordinateReferenceSystem crs) {
    return create(sridSet, crs, new Coordinate());
  }

  static GeometryHelper create(SRIDSet sridSet, CoordinateReferenceSystem crs, Coordinate origin) {
    return new GeometryHelper() {

      @Override
      public SRIDSet getSRIDSet() {
        return sridSet;
      }

      @Override
      public CoordinateReferenceSystem getCRS() {
        return crs;
      }

      @Override
      public Coordinate getRealisticOrigin() {
        return origin;
      }
    };
  }

  SRIDSet getSRIDSet();

  CoordinateReferenceSystem getCRS();

  default CoordinateReferenceSystem getCrs() {
    return getCRS();
  }

  default GeometryFactory getGeometryFactory() {
    return getSRIDSet().getGeometryFactory(getCRS());
  }

  default WKTReader getWKTReader() {
    return new WKTReader(getGeometryFactory());
  }

  default Geometry fromWKT(String wkt) {
    try {
      return getWKTReader().read(wkt);
    } catch (Throwable t) {
      throw new RuntimeException(t);
    }
  }

  default Geometry fromWkt(String wkt) {
    return fromWKT(wkt);
  }

  default Point point(int x, int y) {
    return getGeometryFactory().createPoint(toCoordinate(x, y));
  }

  default Polygon box(int x1, int y1, int x2, int y2) {
    return getGeometryFactory().createPolygon(new Coordinate[]{
      toCoordinate(x1, y1),
      toCoordinate(x2, y1),
      toCoordinate(x2, y2),
      toCoordinate(x1, y2),
      toCoordinate(x1, y1)
    });
  }

  default LineString line(int x1, int y1, int x2, int y2) {
    return line((double) x1, y1, x2, y2);
  }

  default LineString line(double x1, double y1, double x2, double y2) {
    return getGeometryFactory().createLineString(new Coordinate[]{
      toCoordinate(x1, y1),
      toCoordinate(x2, y2)
    });
  }


  /**
   * @return geom reprojected to the CRS from {@link #getCrs() } if necessary.
   */
  default Geometry reproject(Geometry geom) {
    return getSRIDSet().reproject(geom, getSRIDSet().get(getCRS()));
  }

  /**
   * @return envelope reprojected to the CRS from {@link #getCrs() } if necessary.
   */
  default ReferencedEnvelope reproject(ReferencedEnvelope envelope) {
    try {
      return envelope.transform(getCRS(), true);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

  Coordinate getRealisticOrigin();

  default Coordinate toCoordinate(double x, double y) {
    Coordinate origin = getRealisticOrigin();
    /*
     * Implementation note - the previous per-crs implementation for nztm did x/y swapping in this method, but none of
     * the others did.  Only a couple of tests depended on this, and I've swapped those coords instead - I think it's
     * best to keep it consistent - if you're using a northing/easting projection then you should supply the coords in
     * that order.
     */
    return new Coordinate(origin.x + x, origin.y + y);
  }

  default ReferencedEnvelope envelope(Coordinate lowerLeft, Coordinate upperRight) {
    return new ReferencedEnvelope(lowerLeft.x, upperRight.x, lowerLeft.y, upperRight.y, getCRS());
  }

  default ReferencedEnvelope envelopeXYXY(int x1, int y1, int x2, int y2) {
    return envelope(toCoordinate(x1, y1), toCoordinate(x2, y2));
  }

  default Point emptyPoint() {
    return getGeometryFactory().createPoint((CoordinateSequence) null);
  }

  default Point point(double x, double y) {
    return getGeometryFactory().createPoint(toCoordinate(x, y));
  }

  default LineString emptyLine() {
    return getGeometryFactory().createLineString((CoordinateSequence) null);
  }

  default LineString line(Coordinate... coordinates) {
    return getGeometryFactory().createLineString(coordinates);
  }

  default Polygon emptyBox() {
    return getGeometryFactory().createPolygon((CoordinateSequence) null);
  }

  default Polygon box(Coordinate... coordinates) {
    return getGeometryFactory().createPolygon(coordinates);
  }

  default Polygon box(LinearRing shell, LinearRing... holes) {
    return getGeometryFactory().createPolygon(shell, holes);
  }

  default Polygon box(double x1, double y1, double x2, double y2) {
    return box(
        toCoordinate(x1, y1),
        toCoordinate(x2, y1),
        toCoordinate(x2, y2),
        toCoordinate(x1, y2),
        toCoordinate(x1, y1)
    );
  }

  default MultiPoint multiPoint(Point... points) {
    return getGeometryFactory().createMultiPoint(points);
  }

  default MultiLineString multiLine(LineString... lines) {
    return getGeometryFactory().createMultiLineString(lines);
  }

  default MultiCurve multiCurve(LineString... lines) {
    return new MultiCurve(Arrays.asList(lines), getGeometryFactory(), 0.01);
  }

  default MultiPolygon multiBox(Polygon... boxes) {
    return getGeometryFactory().createMultiPolygon(boxes);
  }

  default MultiSurface multiSurface(Polygon... boxes) {
    return new MultiSurface(boxes, getGeometryFactory(), 0.01);
  }

  default CompoundCurve compoundCurve(LineString... lines) {
    return new CompoundCurve(Arrays.asList(lines), getGeometryFactory(), 0.01);
  }

  default CurvePolygon curvePolygon(LinearRing shell, LinearRing... holes) {
    return new CurvePolygon(shell, Arrays.asList(holes), getGeometryFactory(), 0.01);
  }

  /**
   * Return a {@link GeometryCollection) containing geometries. Geometries can be a mixed bag of
   * different geometry types (lines, points and polygons).
   *
   * @param geometries
   * @return
   */
  default GeometryCollection collection(Geometry... geometries) {
    return new GeometryCollection(geometries, getGeometryFactory());
  }

  default LinearRing ring(Coordinate... coordinates) {
    return getGeometryFactory().createLinearRing(coordinates);
  }
}
