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

import java.text.DecimalFormat;

import org.geotools.geometry.jts.ReferencedEnvelope;
import org.geotools.referencing.CRS;
import org.geotools.api.referencing.FactoryException;
import org.geotools.api.referencing.crs.CoordinateReferenceSystem;
import org.geotools.api.referencing.cs.AxisDirection;

import com.google.common.base.CaseFormat;
import com.google.common.collect.ImmutableMap;

import nz.org.riskscape.engine.RiskscapeException;
import nz.org.riskscape.engine.problem.ProblemFactory;
import nz.org.riskscape.problem.Problem;
import nz.org.riskscape.problem.Problems;

/**
 * Tweaks the display of some GeoTools geometry so that it's more user-friendly.
 */
public class GeometryRenderer {

  private interface Errors extends ProblemFactory {
    Problem cannotDisplay(ReferencedEnvelope env, String targetCrs);
  }

  /**
   * Returns the axis-order of the given CRS in a user-friendly string.
   */
  public static String getAxisOrder(CoordinateReferenceSystem crs) {
    ImmutableMap<CRS.AxisOrder, String> axisOrderNames = ImmutableMap.of(
        CRS.AxisOrder.EAST_NORTH, "long,lat / X,Y / Easting,Northing",
        CRS.AxisOrder.NORTH_EAST, "lat,long / Y,X / Northing,Easting",
        CRS.AxisOrder.INAPPLICABLE, "N/A");

    return axisOrderNames.get(CRS.getAxisOrder(crs));
  }

  /**
   * Returns the code we use to refer to the CRS, i.e. what we pass to
   * {@link CRS#decode(String)}. This can often be different to what crs.getName()
   * returns, e.g. "EPSG:4326" rather than "EPSG:WGS 84".
   */
  public static String getCode(CoordinateReferenceSystem crs) {
    try {
      Integer code = CRS.lookupEpsgCode(crs, false);
      if (code != null) {
        return "EPSG:" + code.toString();
      }
    } catch (FactoryException ex) {
      // just use default below
    }
    // fallback to just using the CRS name
    return crs.getName().toString();
  }

  /**
   * Displays the {@link AxisDirection} for the given axis (i.e. dimension=0 for
   * x-axis, 1 for y). Typically this will display "North" and "East", but there
   * are a wide range of axis directions.
   */
  public static String getAxisDirection(CoordinateReferenceSystem crs, int dimension) {
    AxisDirection direction = crs.getCoordinateSystem().getAxis(dimension).getDirection();
    return CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, direction.identifier());
  }

  /**
   * Displays the bounds of an envelope. The important difference this has over
   * the vanilla GeoTools toString() is that we display the x,y direction that the
   * coordinates are in (i.e. x=North), along with the EPSG code of the CRS.
   */
  public static String getBounds(ReferencedEnvelope env) {
    // show up to 4 decimal places (~11m in WGS84), with minimum of one decimal place
    DecimalFormat df = new DecimalFormat("#.0###");
    CoordinateReferenceSystem crs = env.getCoordinateReferenceSystem();
    return String.format("%s [%s : %s %s, %s : %s %s]",
        getCode(crs),
        df.format(env.getMinX()),
        df.format(env.getMaxX()),
        getAxisDirection(crs, 0),
        df.format(env.getMinY()),
        df.format(env.getMaxY()),
        getAxisDirection(crs, 1));
  }

  /**
   * Displays the bounds in the given targetCrs. This can be handy when you have
   * geometry in a different CRS, but want to display it in a CRS that the user is
   * familiar with (e.g. WGS84).
   */
  public static String getBoundsInCrs(ReferencedEnvelope envelope, CoordinateReferenceSystem targetCrs) {
    ReferencedEnvelope transformedBounds = null;
    try {
      transformedBounds = envelope.transform(targetCrs, true);
    } catch (Exception ex) {
      // cannot convert - the envelope's coordinates maybe in the wrong CRS
      throw new RiskscapeException(
          Problems.get(Errors.class).cannotDisplay(envelope, getCode(targetCrs))
              .withChildren(Problems.caught(ex)));
    }
    return getBounds(transformedBounds);
  }

  /**
   * @return true if the 2 CRSs are roughly equivalent (at least for display purposes).
   * The 2 CRSs may still have differences, like axis orientation for example.
   * The point is to avoid displaying fundamentally the same coordinates twice.
   */
  public static boolean isCrsEquivalent(CoordinateReferenceSystem a, CoordinateReferenceSystem b) {
    if (getCode(a).equals(getCode(b))) {
      // we would display them with the same CRS name, even if axis-order is flipped
      return true;
    }
    // check with geotools, just to be sure
    return CRS.equalsIgnoreMetadata(a, b);
  }
}
