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

import org.geotools.geometry.jts.ReferencedEnvelope;
import org.geotools.referencing.CRS;
import org.locationtech.jts.geom.Envelope;
import org.geotools.api.referencing.FactoryException;
import org.geotools.api.referencing.crs.CoordinateReferenceSystem;

import lombok.EqualsAndHashCode;
import lombok.Getter;

/**
 * Type that adds {@link CoordinateReferenceSystem} and an optional bounds to another type.
 *
 * NB This class can wrap any type, not just geometry, so care should be taken when finding Referenced types to ensure
 * that they are also Geometry types before casting the values to Geometry.
 */
@EqualsAndHashCode
public class Referenced implements WrappingType {

  /**
   * Static constructor that takes care of re-wrapping the produced referenced type with nullable if the given
   * underlying type was nullable
   */
  public static Type ofNullable(Type underlying, CoordinateReferenceSystem crs) {
    return Nullable.rewrap(underlying, nn -> new Referenced(nn, crs, null));
  }

  /**
   * Static constructor that takes care of re-wrapping the produced referenced type with nullable if the given
   * underlying type was nullable
   */
  public static Type ofNullable(Type underlying, ReferencedEnvelope bounds) {
    return Nullable.rewrap(underlying, nn -> new Referenced(nn, bounds.getCoordinateReferenceSystem(), bounds.copy()));
  }

  /**
   * Static constructor that takes care of re-wrapping the produced referenced type with nullable if the given
   * underlying type was nullable
   */
  public static Type ofNullable(Type underlying, CoordinateReferenceSystem crs, Envelope envelope) {
    return Nullable.rewrap(underlying, nn -> new Referenced(nn, crs, envelope));
  }

  /**
   * Now somewhat needless static constructor to avoid undue change in code that was calling it.
   * NB static constructors are most useful when they do something that isn't possible in a vanilla constructor, such
   * as handing out frequently used instances to avoid unnecessary promulgation of objects, or having some extra logic
   * that might affect the return type, or perhaps giving it a more meaningful name in the case it accepts different
   * arguments.  I had originally started remove all the uses of this method, but it seemed petty so i've left them,
   * but know that this method does nothing special beyond constructing an instance.
   */
  public static Type of(Type underlying, CoordinateReferenceSystem crs, Envelope envelope) {
    return new Referenced(underlying, crs, envelope);
  }

  /**
   * Now somewhat needless static constructor to avoid undue change in code that was calling it.
   * NB static constructors are most useful when they do something that isn't possible in a vanilla constructor, such
   * as handing out frequently used instances to avoid unnecessary promulgation of objects, or having some extra logic
   * that might affect the return type, or perhaps giving it a more meaningful name in the case it accepts different
   * arguments.  I had originally started remove all the uses of this method, but it seemed petty so i've left them,
   * but know that this method does nothing special beyond constructing an instance.
   */
  public static Type of(Type underlying, CoordinateReferenceSystem crs) {
    return new Referenced(underlying, crs);
  }

  /**
   * Convenience constructor that takes the crs and bounds from the given referenced envelope
   */
  public Referenced(Type underlying, ReferencedEnvelope envelope) {
    this(underlying, envelope.getCoordinateReferenceSystem(), envelope);
  }

  /**
   * Convenience constructor that omits the bounds from the Referenced type.
   */
  public Referenced(Type underlying, CoordinateReferenceSystem crs) {
    this(underlying, crs, null);
  }

  /**
   * Create a new Referenced type that wraps the given type with a crs and a bounds envelope.
   * @param underlying not Nullable, not already Referenced, Type.  Use one of the ofNullable constructors if the given
   * type might be nullable
   * @param crs a {@link CoordinateReferenceSystem} to associate with the given type.  Can not be null.
   * @param envelope an optional envelope to associate with the geometry.  If this is given then it is expected that all
   * geometry that emerges from this type will be within the bounds of the envelope.  Can be null
   * @throws IllegalArgumentException if the type is nullable or already wrapped in a referenced type.
   */
  public Referenced(Type underlying, CoordinateReferenceSystem crs, Envelope envelope) {
    if (Nullable.is(underlying)) {
      throw new IllegalArgumentException("can not wrap a nullabe type in underlying - use Nullable#apply");
    }

    if (underlying.find(Referenced.class).isPresent()) {
      // NB this should probably be enforced for all wrapping types...
      throw new IllegalArgumentException("Can not wrap an already referenced type");
    }

    if (crs == null) {
      throw new NullPointerException("CRS can not be null");
    }

    this.underlyingType = underlying;
    this.crs = crs;
    this.envelope = envelope;
  }

  @Getter
  private final Type underlyingType;

  @Getter
  private final CoordinateReferenceSystem crs;

  @Getter
  private final Envelope envelope;

  public ReferencedEnvelope getBounds() {
    return envelope == null ? null : new ReferencedEnvelope(envelope, crs);
  }

  @Override
  public Object coerce(Object value) throws CoercionException {
    return getUnderlyingType().coerce(value);
  }

  @Override
  public Class<?> internalType() {
    return getUnderlyingType().internalType();
  }

  /**
   * Returns a new Type with underlyingType of toWrap with the same crs and bounds as this
   * referenced.
   *
   * @param toWrap type to reference with this crs/bounds
   * @return referenced toWrap
   */
  public Type wrapNullable(Type toWrap) {
    return Referenced.ofNullable(toWrap, crs, envelope);
  }

  /**
   * Returns a new Type with underlyingType of toWrap with the same crs and bounds as this
   * referenced.
   *
   * @param toWrap type to reference with this crs/bounds
   * @return referenced toWrap
   */
  public Referenced wrap(Type toWrap) {
    return new Referenced(toWrap, crs, envelope);
  }

  @Override
  public String toString() {
    String crsCode = null;
    try {
      crsCode = CRS.lookupIdentifier(crs, false);
    } catch (FactoryException ex) {
      // we ignore factory exceptions here as the lookup is a convenience. we will fallback to
      // displaying the full CRS.toSting() output
    }
    // displaying "geometry-type[crs=xxx]" is nicer for users as we often just use the toString for
    // types. But we know this is a referenced thing because of the CRS information. Similary the bounds
    // is removed as that makes the label look a little over bearing.
    return String.format("%s[crs=%s]",
        underlyingType,
        crsCode != null ? crsCode : crs.toWKT());
  }
}
