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

import org.geotools.api.referencing.crs.CoordinateReferenceSystem;
import org.geotools.coverage.grid.GridCoordinates2D;
import org.geotools.coverage.grid.GridCoverage2D;
import org.geotools.geometry.Position2D;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.Point;
import org.locationtech.jts.geom.Polygon;

import it.geosolutions.jaiext.jts.CoordinateSequence2D;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import nz.org.riskscape.engine.geo.OverlayOperations;

/**
 * Represents a particular cell within a {@link FeatureGrid}
 */
@EqualsAndHashCode(exclude = "featureGrid")
@ToString(of = {"x", "y"})
public class FeatureGridCell {

  private final FeatureGrid featureGrid;

  // counters for the position of this cell within the featureGrid.  These are
  // relative to the feature's grid, not the entire grid
  private final int x;
  private final int y;

  FeatureGridCell(FeatureGrid featureGrid, int x, int y) {
    this.featureGrid = featureGrid;
    this.x = x;
    this.y = y;
  }

  /**
   * @return a jts {@link Point} geometry that locates the centre of this grid cell
   */
  public Point getCellCentre() {
    Position2D topLeft = featureGrid.getFeatureTopLeft();
    double px = topLeft.x + (x * featureGrid.getCellWorldX());
    double py = topLeft.y + (y * featureGrid.getCellWorldY());

    return featureGrid.getGeometryFactory().createPoint(new Coordinate(px, py));
  }

  /**
   * @return a jts {@link Polygon} geometry that surrounds this grid cell
   */
  public Polygon getCellPolygon() {
    Point point = getCellCentre();

    double halfWidth = featureGrid.getCellWorldX() / 2;
    double halfHeight = featureGrid.getCellWorldY() / 2;

    double x1 = point.getX() - halfWidth;
    double x2 = point.getX() + halfWidth;
    double y1 = point.getY() - halfHeight;
    double y2 = point.getY() + halfHeight;

    return featureGrid.getGeometryFactory().createPolygon(new CoordinateSequence2D(
        x1, y1,
        x1, y2,
        x2, y2,
        x2, y1,
        x1, y1
    ));
  }

  /**
   * @return the intersection of the {@link FeatureGrid}'s geometry and grid, returning all parts of the
   * intersection.
   */
  public Geometry computeIntersection() {
    OverlayOperations ops = OverlayOperations.get();
    return ops.intersection(getCellPolygon(), featureGrid.getFeature());
  }

  /**
   * @return true if this grid cell intersects the input feature geometry
   */
  public boolean intersects() {
    return getCellPolygon().intersects(featureGrid.getFeature());
  }

  /**
   * @return the grid coordinates of this cell relative to the {@link FeatureGrid}'s overall grid.  This can be used
   * to sample a {@link GridCoverage2D} that is built on the same grid.
   */
  public GridCoordinates2D getGridPosition() {
    return new GridCoordinates2D(x + featureGrid.getGridOffsetX(), y + featureGrid.getGridOffsetY());
  }

  /**
   * @return the CRS of this grid cell
   */
  public CoordinateReferenceSystem getCRS() {
    return featureGrid.getGridGeometry().getCoordinateReferenceSystem();
  }
}
