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

import java.util.Optional;

import org.geotools.coverage.grid.GridEnvelope2D;
import org.geotools.coverage.grid.GridGeometry2D;
import org.geotools.geometry.Position2D;
import org.geotools.geometry.jts.ReferencedEnvelope;
import org.locationtech.jts.geom.Point;
import org.geotools.api.geometry.Position;
import org.geotools.api.geometry.Bounds;
import org.geotools.api.referencing.crs.CoordinateReferenceSystem;
import org.geotools.api.referencing.operation.MathTransform;
import org.geotools.api.referencing.operation.TransformException;

import nz.org.riskscape.engine.SRIDSet;
import nz.org.riskscape.engine.coverage.TypedCoverage;
import nz.org.riskscape.engine.types.Type;

/**
 * Provides TypedCoverage that maps an underlying dataset to latitude and
 * longitude coordinates. An example usage is providing coverage for a
 * 2-dimensional dataset read from a HDF5 shakemap file.
 */
public class DatasetCoverage implements TypedCoverage {

  public enum GridStartPoint {
    NORTH_WEST_CORNER,
    NORTH_EAST_CORNER,
    SOUTH_EAST_CORNER,
    SOUTH_WEST_CORNER
  }
  private final Dataset2D dataPoints;
  private final GridGeometry2D gridGeometry;
  private final Bounds sourceExtent;
  private final MathTransform crsToGrid;
  private final GridStartPoint dataStartsAt;
  private final CoverageValueProviderHelper helper;

  /**
   * Creates a new TypedCoverage for a given dataset and its corresponding coordinates
   * @param sourceExtent the latitude/longitude coordinates
   * that this grid corresponds to
   * @param dataPoints the underlying dataset
   * @param dataStartsAt the corner of the grid corresponding to index 0,0
   */
  public DatasetCoverage(Bounds sourceExtent, Dataset2D dataPoints,
      GridStartPoint dataStartsAt, SRIDSet sridSet) {
    this.dataPoints = dataPoints;
    this.sourceExtent = sourceExtent;
    this.dataStartsAt = dataStartsAt;
    this.helper = new CoverageValueProviderHelper(
          new ReferencedEnvelope(sourceExtent), sridSet);

    /* create a mapping between the lat/long envelope and the 2D dataset grid */
    this.gridGeometry = new GridGeometry2D(
        new GridEnvelope2D(0, 0, (int)dataPoints.getWidth(), (int)dataPoints.getHeight()),
        sourceExtent);

    // we'll want to convert from lat/long back to grid x/y. Build the transform now.
    // Note that GridGeometry2D.getCRSToGrid2D(PixelOrientation) maps the pixel relative
    // to PixelOrientation#CENTER by default
    this.crsToGrid = gridGeometry.getCRSToGrid2D();
  }

  @Override
  public Type getType() {
    return dataPoints.getType();
  }

  private Position convertToGridPosition(Point point) {
    Position dest = new Position2D();
    try {
      crsToGrid.transform(new Position2D(point.getX(), point.getY()), dest);
    } catch (TransformException e) {
      throw new RuntimeException(e);
    }
    return dest;
  }

  @Override
  public Object evaluate(Point inputPoint) {
    try {
      Point point = (Point) helper.reprojectIfNecessary(inputPoint);

      // convert the lat/long point back to x/y grid co-ordinates.
      // Note that the crsToGrid transform is relative to the pixel centre,
      // so we need to round the 2D position to get the correct x,y position.
      // E.g. pixel top-left would be -0.5 offset for x/y, bottom-right is offset +0.5
      Position gridPosition = convertToGridPosition(point);
      long x = Math.round(gridPosition.getOrdinate(0));
      long y = Math.round(gridPosition.getOrdinate(1));

      if (dataPoints.isInBounds(x, y)) {
        return dataPoints.getValue(x, y);
      }

      /* point falls outside our grid bounds */
      return null;
    } catch (CoverageValueProviderHelper.EmptyGeometryException e) {
      // you can't sample a coverage with an empty point
      return null;
    }
  }

  @Override
  public CoordinateReferenceSystem getCoordinateReferenceSystem() {
    return gridGeometry.getCoordinateReferenceSystem();
  }

  @Override
  public Optional<ReferencedEnvelope> getEnvelope() {
    return Optional.of(helper.getEnvelope());
  }

}
