/*
 * 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.output;

import java.net.URI;
import java.util.Optional;

import org.geotools.referencing.CRS;
import org.locationtech.jts.geom.CoordinateFilter;
import org.locationtech.jts.geom.Geometry;
import org.geotools.api.referencing.FactoryException;
import org.geotools.api.referencing.crs.CoordinateReferenceSystem;

import lombok.Getter;
import lombok.RequiredArgsConstructor;
import nz.org.riskscape.engine.SRIDSet;
import nz.org.riskscape.engine.problem.ProblemFactory;
import nz.org.riskscape.engine.problem.SeverityLevel;
import nz.org.riskscape.problem.Problem;
import nz.org.riskscape.problem.ProblemSink;
import nz.org.riskscape.problem.Problems;

/**
 * Utility for swapping {@link Geometry} coordinate order, typically so that it's in the right order for writing where
 * an output format demands a particular axis order.
 */
@RequiredArgsConstructor @Getter
public class AxisSwapper {

  public interface LocalProblems extends ProblemFactory {
    /**
     * When a shapefile is being written with geometries in a {@link CoordinateReferenceSystem} that has
     * a YX axis order and RiskScape is not able to create an equivalent CRS with XY axis order. This will
     * mean that the .prj file may have incorrect axis information
     * place.
     * NB the error message is currently shapefile specific - if we end up using this for other formats, we'll need to
     * parameterize or have format specific messages.
     */
    @SeverityLevel(Problem.Severity.WARNING)
    Problem axisOrderIncorrectInPrj();
  }

  public static final LocalProblems PROBLEMS = Problems.get(LocalProblems.class);

  /**
   * Returns an AxisSwapper that will flip coordinates to x-y ordering, or empty if the crs is already in x-y order.
   * If a flipped crs could not be created, a swapper is still returned, but `newCrs` is set to be the original y-x
   * crs.  If required, we could change this to be optional, but at the moment we would prefer an incorrect prj to no
   * prj, so it is set to simplify writer logic.
   * @param crs the crs that geometries are in.
   * @param storedAt used for context if there's a problem with the CRS
   * @param problemSink a place to dump a problem if no flipped CRS could be created
   */
  public static Optional<AxisSwapper> getForceXY(
      CoordinateReferenceSystem crs,
      URI storedAt,
      ProblemSink problemSink
  ) {
    if (CRS.getAxisOrder(crs) == CRS.AxisOrder.NORTH_EAST) {
      // The crs has an YX axis order. lets attempt to get an XY version of the same crs. this will
      // only work for a CRS that has come from an EPSG code (such has EPSG:2193), which should cover
      // most cases.
      Integer epsgCode = lookupEpsgCode(crs);

      CoordinateReferenceSystem newCrs;
      if (epsgCode == null) {
        // no epsg code means we can't reconstruct the CRS with the axis order flipped.
        // The shapefile's x-y order is more important than the prj being correct, so
        // we go with an incorrect prj and correct shapefile order (rather than failing)
        problemSink.log(Problems.foundWith(storedAt, PROBLEMS.axisOrderIncorrectInPrj()));
        newCrs = crs;
      } else {
        newCrs = SRIDSet.epsgToCrsWithForceXY("EPSG:" + epsgCode);
      }
      return Optional.of(new AxisSwapper(newCrs));
    } else {
      return Optional.empty();
    }
  }

  /**
   * Returns an {@link AxisSwapper} that flips coordinates to the order defined in the CRS's canonical EPSG definition,
   * or empty if the CRS is the canonical version for.  We say canonical definition, as a CRS can loosely match another
   * CRS by ESPG code but have different axis order (such as if it's been loaded from a shapefile).  This method will
   * normalize the axis order so that it matches the canonically defined order.  Or empty if no EPSG code could be
   * matched or if the crs already matches the EPSG defined order.
   */
  public static Optional<AxisSwapper> getForceEpsgDefined(CoordinateReferenceSystem crs) {
    Integer epsgCode = lookupEpsgCode(crs);
    if (epsgCode != null) {
      CoordinateReferenceSystem crsDefined = SRIDSet.epsgToCrs("EPSG:" + epsgCode);
      if (CRS.getAxisOrder(crs) != CRS.getAxisOrder(crsDefined)) {
        return Optional.of(new AxisSwapper(crsDefined));
      }
    }
    return Optional.empty();
  }

  private static Integer lookupEpsgCode(CoordinateReferenceSystem crs) {
    try {
      return CRS.lookupEpsgCode(crs, false);
    } catch (FactoryException ex) {
      // looks like this only happens in the rare case than the identifier metadata can not be parsed in to an int
    }
    return null;
  }

  /**
   * A coordinate reference system with the desired ordering, or the original crs if none could be created
   */
  private final CoordinateReferenceSystem newCrs;

  public static final CoordinateFilter AXIS_SWAPPING_FILTER = coordinate -> {
    double oldX = coordinate.x;
    coordinate.x = coordinate.y;
    coordinate.y = oldX;
  };

  /**
   * @return a new geometry based on the input geometry, but with X and Y coordinates swapped
   */
  public Geometry swapAxis(Geometry geom) {
    Geometry clone = geom.copy();
    clone.apply(AXIS_SWAPPING_FILTER);
    clone.geometryChanged();
    return clone;
  }

}
