/*
 * 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 static nz.org.riskscape.engine.GeoHelper.*;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;

import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

import org.geotools.api.geometry.Bounds;
import org.geotools.api.geometry.Position;
import org.geotools.geometry.Position2D;
import org.geotools.geometry.jts.ReferencedEnvelope;
import org.geotools.referencing.CRS;
import org.junit.Before;
import org.junit.Test;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.Envelope;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.GeometryFactory;
import org.locationtech.jts.geom.LineString;
import org.locationtech.jts.geom.Polygon;

import com.google.common.collect.Lists;

import nz.org.riskscape.engine.ProjectTest;
import nz.org.riskscape.engine.SRIDSet;
import nz.org.riskscape.engine.Tuple;
import nz.org.riskscape.engine.bind.BindingContext;
import nz.org.riskscape.engine.coverage.TypedCoverage;
import nz.org.riskscape.engine.data.Bookmark;
import nz.org.riskscape.engine.defaults.data.ShapefileBookmarkResolver;
import nz.org.riskscape.engine.grid.FeatureGrid;
import nz.org.riskscape.engine.gt.GeometryHelper;
import nz.org.riskscape.engine.relation.Relation;
import nz.org.riskscape.engine.types.Type;
import nz.org.riskscape.engine.types.Types;
import nz.org.riskscape.engine.util.Pair;

public class GridTypedCoveragePolygonTest extends ProjectTest {

  SRIDSet sridSet = project.getSridSet();
  GeometryHelper nztmHelper = GeometryHelper.nzTransverseMercatorWithOriginShift(sridSet);
  GeometryFactory factory = nztmHelper.getGeometryFactory();

  Type type = Types.FLOATING;
  Bounds envelope = ReferencedEnvelope.rect(0, 0, 10, 10, nztmHelper.getCRS());

  TypedCoverage subject;

  Position directPosition = new Position2D(nztmHelper.getCRS(), 1, 2);

  BindingContext context = project.newBindingContext();
  Relation features;

  Path testDir = Paths.get("src", "test", "resources", "nz", "org", "riskscape", "engine", "data", "coverage");
  String desc;
  GridTypedCoverage coverage;
  List<Pair<Geometry, Object>> results;
  ShapefileBookmarkResolver resolver;


  @Before
  public void setup() {
    this.resolver = new ShapefileBookmarkResolver(engine);

    CoverageFileBookmarkResolver covResolver = new CoverageFileBookmarkResolver(engine);
    coverage = (GridTypedCoverage) covResolver.resolve(Bookmark.fromURI(
        testDir.resolve("polygon-test.asc").toUri()), executionContext).get()
        .getData(TypedCoverage.class).get();
  }

  @Test
  public void aVerticalLineGivesAllPixelsUnderneath() throws Exception {
    features = load("lines.shp");
    desc = "vertical";

    assertGridEnvelope(5, 6, 0, 10);
    assertWorldEnvelope(1780410, 1780411, 5435354, 5435364);
    assertPixelValues(5, 15, 25, 35, 45, 55, 65, 75, 85, 95);

    // one side of the cell intersects
    assertGeometryWithValue(5, factory.createLineString(new Coordinate[] {
        new Coordinate(1780410.6, 5435363.45),
        new Coordinate(1780410.57, 5435363),
    }));

    // both sides of the cell intersects
    assertGeometryWithValue(75, factory.createLineString(new Coordinate[] {
        new Coordinate(1780410.6, 5435357),
        new Coordinate(1780410.6, 5435356),
    }));
  }

  @Test
  public void aHorizontalLineGivesAllPixelsUnderneath() throws Exception {
    features = load("lines.shp");
    desc = "horizontal";

    assertGridEnvelope(0, 10, 5, 6);
    assertWorldEnvelope(1780405, 1780415, 5435358, 5435359);
    assertPixelValues(50, 51, 52, 53, 54, 55, 56, 57, 58, 59);
  }

  @Test
  public void aShortLineGivesAllPixelsUnderneath() throws Exception {
    features = load("lines.shp");
    desc = "short-diagonal";

    assertGridEnvelope(6, 8, 2, 5);
    assertWorldEnvelope(1780411, 1780413, 5435359, 5435362);
    assertPixelValues(27, 36, 37, 46);
  }

  @Test
  public void aLongMeanderingLineGivesAllPixelsUnderneath() throws Exception {
    desc = "meandering";
    features = load("lines.shp");

    assertGridEnvelope(0, 5, 0, 2);
    assertWorldEnvelope(1780405, 1780410, 5435362, 5435364);
    assertPixelValues(10, 11, 12, 13, 14, 2, 3, 4);

    // many intersections
    assertGeometryWithValue(12, factory.createMultiLineString(new LineString[] {
        factory.createLineString(new Coordinate[] {
            new Coordinate(1780407, 5435362.9),
            new Coordinate(1780407.2, 5435363)
        }),
        factory.createLineString(new Coordinate[] {
            new Coordinate(1780408, 5435362.8),
            new Coordinate(1780407.5, 5435362.5),
            new Coordinate(1780408, 5435362.5)
        })
    }));
  }

  @Test
  public void aLineThatCrossesTheGridGivesPixelsUnderneath() throws Exception {
    desc = "crosses";
    features = load("lines.shp");

    // the envelope intersection includes a cell that won't intersect
    assertGridEnvelope(8, 10, 9, 10);
    assertWorldEnvelope(1780413, 1780415, 5435354, 5435355);
    assertPixelValues(99);

    assertGeometryWithValue(99, factory.createLineString(new Coordinate[] {
        new Coordinate(1780414.5, 5435354),
        new Coordinate(1780415, 5435354.5)
    }));
  }

  @Test
  public void anEmptyGeomReturnsNoPixels() {
    // there should be no intersection (and no exceptions) finding the intersection with an empty
    // geometry
    Polygon empty = factory.createPolygon();
    empty.setSRID(sridSet.get(nztmHelper.getCRS()));
    assertThat(coverage.evaluateIntersection(empty), hasSize(0));
  }

  @Test
  public void geometriesAreReprojectedInAndOut() throws Exception {
    features = load("lines-nzgd.shp");
    // my only friend
    desc = "friend";

    assertPixelValues(76, 77, 67);
    assertGridEnvelope(6, 8, 6, 8);
    assertWorldEnvelope(1780411, 1780413, 5435356, 5435358);

    assertGeometryWithValue(76, factory.createLineString(new Coordinate[] {
        new Coordinate(175.152040913104, -41.213073),
        new Coordinate(175.152047, -41.213069)
    }), 6);

  }

  @Test
  public void aSmallPolygonThatIntersectsASingleCell() throws Exception {
    features = load("polys.shp");
    desc = "small";

    assertGridEnvelope(7, 8, 1, 2);
    assertWorldEnvelope(1780412, 1780413, 5435362, 5435363);
    assertPixelValues(17);

    assertGeometryWithValue(17, factory.createPolygon(new Coordinate[] {
        new Coordinate(1780412.1, 5435363),
        new Coordinate(1780412.9, 5435362.9),
        new Coordinate(1780412.9, 5435362.1),
        new Coordinate(1780412.5, 5435362.5),
        new Coordinate(1780412.1, 5435362.2),
        new Coordinate(1780412.1, 5435363)
    }));
  }

  @Test
  public void aPolygonThatCrossesTheGrid() throws Exception {
    features = load("polys.shp");
    desc = "crosses";

    assertGridEnvelope(0, 4, 0, 2);
    // I think we have enough world coord assertions now - it's the same routine

    assertPixelValues(1, 2, 10, 11);

    assertGeometryWithValue(11, factory.createPolygon(new Coordinate[] {
        new Coordinate(1780406, 5435363),
        new Coordinate(1780406.8, 5435363),
        new Coordinate(1780406.2, 5435362.3),
        new Coordinate(1780406, 5435362.4),
        new Coordinate(1780406, 5435363)
    }));
  }

  @Test
  public void aPolygonThatIntersectsMultipleCells() throws Exception {
    features = load("polys.shp");
    desc = "medium";

    assertGridEnvelope(3, 6, 5, 9);
    assertPixelValues(53, 54, 63, 64, 65, 73, 74, 75, 83, 84);

    assertGeometryWithValue(54, factory.createPolygon(new Coordinate[] {
        new Coordinate(1780409.0000, 5435358.0000),
        new Coordinate(1780409.0121, 5435358.0000),
        new Coordinate(1780409.0000, 5435358.0064),
        new Coordinate(1780409.0000, 5435358.0000)
    }), 4);
  }

  @Test
  public void aPolygonThatDoesNotIntersect() throws Exception {
    features = load("polys.shp");
    desc = "outside";

    // an empty envelope
    assertThat(assertGridEnvelope(0, -1, 0, -1), is(new Envelope()));
    assertPixelValues();
  }


  private void assertGeometryWithValue(int value, Geometry geometry) {
    assertGeometryWithValue(value, geometry, 1);
  }

  private void assertGeometryWithValue(int value, Geometry geometry, int roundTo) {
    for (Pair<Geometry, Object> pair : results) {
      if (Integer.valueOf(value).equals(Double.valueOf(pair.getRight().toString()).intValue())) {

        LinkedList<Coordinate> expected =
            Lists.newLinkedList(Arrays.asList(roundCoordinates(geometry.getCoordinates(), roundTo)));

        LinkedList<Coordinate> actual =
            Lists.newLinkedList(Arrays.asList(roundCoordinates(pair.getLeft().getCoordinates(), roundTo)));

        if (geometry instanceof Polygon) {
          // unclose the shape - just makes equality difficult
          assertEquals(expected.getLast(), expected.getFirst());
          assertEquals(actual.getLast(), actual.getFirst());
          expected.removeLast();
          actual.removeLast();
        }

        int size = expected.size();
        while (size > 0) {
          size--;
          expected.addLast(expected.removeFirst());

          if (expected.equals(actual)) {
            return;
          }
        }

        Collections.reverse(actual);
        size = expected.size();
        while (size > 0) {
          size--;
          expected.addLast(expected.removeFirst());

          if (expected.equals(actual)) {
            return;
          }
        }

        // produces a nicer failure message
        assertEquals(expected, actual);
      }
    }

    fail("could not find value amogn results");
  }

  private void assertWorldEnvelope(int minX, int maxX, int minY, int maxY) throws Exception {
    FeatureGrid griddedGeometry =
        new FeatureGrid(
            getReprojectedFeatureGeometry(),
            CRS.getAxisOrder(coverage.getCoverage().getCoordinateReferenceSystem()),
            coverage.getCoverage().getGridGeometry()
        );

    org.locationtech.jts.geom.Envelope env = griddedGeometry.getFeatureGridEnvelopeInWorldCrs();
    assertEquals("minx", minX, (int) env.getMinX());
    assertEquals("miny", minY, (int) env.getMinY());
    assertEquals("maxx", maxX, (int) env.getMaxX());
    assertEquals("maxy", maxY, (int) env.getMaxY());
  }

  private Envelope assertGridEnvelope(int minX, int maxX, int minY, int maxY) throws Exception {
    FeatureGrid griddedGeometry =
        new FeatureGrid(
            getReprojectedFeatureGeometry(),
            CRS.getAxisOrder(coverage.getCoverage().getCoordinateReferenceSystem()),
            coverage.getCoverage().getGridGeometry()
        );

    org.locationtech.jts.geom.Envelope env = griddedGeometry.getEnvelope();
   assertEquals("minx", minX, (int) env.getMinX());
   assertEquals("miny", minY, (int) env.getMinY());
   assertEquals("maxx", maxX, (int) env.getMaxX());
   assertEquals("maxy", maxY, (int) env.getMaxY());
   return env;
  }


  private Geometry getFeatureGeometry() {
    Tuple feature = features.stream().filter(t -> desc.equals(t.fetch("desc"))).findFirst().orElse(null);
    if (feature == null) {
      fail("No line named " + desc);
      return null;
    } else {
      return feature.fetch("the_geom");
    }
  }

  private Geometry getReprojectedFeatureGeometry() {
    Geometry geom = getFeatureGeometry();
    int gridSrid = sridSet.get(coverage.getCoverage().getCoordinateReferenceSystem());

    if (geom.getSRID() != gridSrid) {
      return sridSet.reproject(geom, gridSrid);
    } else {
      return geom;
    }
  }

  private void assertPixelValues(int... expectedValues) {
    Tuple feature = features.stream().filter(t -> desc.equals(t.fetch("desc"))).findFirst().orElse(null);
    if (feature == null) {
      fail("No line named " + desc);
    }

    Function<Geometry, List<Pair<Geometry, Object>>> function =
        coverage.getEvaluateIntersectionOp().orElseThrow(() -> new AssertionError("Coverage does not support this op"));

    this.results = function.apply(feature.fetch("the_geom"));
    Set<Integer> collected = results.stream().map(p -> Double.valueOf(p.getRight().toString()).intValue())
        .collect(Collectors.toSet());

    Set<Integer> expected = new HashSet<>();
    for (int i = 0; i < expectedValues.length; i++) {
      expected.add(expectedValues[i]);
    }
    assertEquals(expected, collected);

  }

  private Relation load(String filename) {
    return resolver.resolve(Bookmark.fromURI(testDir.resolve(filename).toUri()), executionContext).get()
        .getData(Relation.class).get();
  }

}
