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

import java.util.ArrayList;
import java.util.List;

import org.junit.Test;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.LineString;
import org.locationtech.jts.geom.Point;
import org.locationtech.jts.geom.Polygon;

import com.google.common.collect.Lists;

import nz.org.riskscape.engine.SRIDSet;
import nz.org.riskscape.engine.Tuple;
import nz.org.riskscape.engine.geo.GeometryUtils;
import nz.org.riskscape.engine.gt.GeometryHelper;
import nz.org.riskscape.engine.relation.ListRelation;
import nz.org.riskscape.engine.relation.SpatialMetadata;
import nz.org.riskscape.engine.types.Nullable;
import nz.org.riskscape.engine.types.Struct;
import nz.org.riskscape.engine.types.Types;
import nz.org.riskscape.engine.util.Pair;
import nz.org.riskscape.problem.ProblemSink;

public class SpatialRelationTypedCoverageTest {

  SRIDSet sridSet = spy(new SRIDSet());
  GeometryHelper nztmHelper = GeometryHelper.nzTransverseMercatorWithOriginShift(sridSet);
  GeometryHelper latLongHelper = GeometryHelper.latLong(sridSet);

  Struct relationType = Struct.of("geom", Types.GEOMETRY, "name", Types.TEXT);

  Tuple t1 = Tuple.ofValues(relationType, nztmHelper.box(100, 100, 200, 200), "one");
  Tuple t2 = Tuple.ofValues(relationType, nztmHelper.box(200, 100, 300, 200), "two");
  Tuple t3 = Tuple.ofValues(relationType, nztmHelper.box(300, 100, 400, 200), "three");

  Tuple pt1 = Tuple.ofValues(relationType, nztmHelper.point(100, 100), "point one");
  Tuple pt2 = Tuple.ofValues(relationType, nztmHelper.point(200, 100), "point two");
  Tuple pt3 = Tuple.ofValues(relationType, nztmHelper.point(300, 100), "point three");

  SpatialRelationTypedCoverage subject;
  SpatialRelationTypedCoverage pointySubject;

  public SpatialRelationTypedCoverageTest() {
    SpatialMetadata sm = new SpatialMetadata(nztmHelper.getCrs(), relationType.getEntry("geom"));

    List<Tuple> tuples = Lists.newArrayList(t1, t2, t3);
    ListRelation relation = new ListRelation(relationType, tuples, sm);

    subject = SpatialRelationTypedCoverage.of(relation, sridSet, ProblemSink.DEVNULL).get();

    List<Tuple> pointyTuples = Lists.newArrayList(pt1, pt2, pt3);
    ListRelation pointyRelation = new ListRelation(relationType, pointyTuples, sm);
    pointySubject = SpatialRelationTypedCoverage.of(pointyRelation, sridSet, ProblemSink.DEVNULL).get();
  }

  @Test
  public void findsIntersectingPoint() {
    assertThat(subject.evaluate(nztmHelper.point(150, 150)), is(t1));

    // On boundary of two features
    assertThat(subject.evaluate(nztmHelper.point(200, 150)), oneOf(t1, t2));

    // on outside edge of one feature
    assertThat(subject.evaluate(nztmHelper.point(400, 200)), is(t3));
  }

  @Test
  public void findsIntersectingPointFromOtherCRS() {
    Point nzPoint = nztmHelper.point(150, 150);
    Point latLongPoint = (Point) latLongHelper.reproject(nzPoint);

    assertThat(nzPoint, not(latLongPoint));

    assertThat(subject.evaluate(latLongPoint), is(t1));
  }

  @Test
  public void findsAllIntersectingLines() {
    assertThat(subject.getCoordinateReferenceSystem(), is(nztmHelper.getCrs()));
    assertThat(subject.getType(), is(Nullable.of(relationType)));

    assertThat(subject.evaluateIntersection(nztmHelper.line(150, 150, 350, 150)),
        containsInAnyOrder(isPair(isGeometry(nztmHelper.line(150, 150, 200, 150)), is(t1)),
            isPair(isGeometry(nztmHelper.line(200, 150, 300, 150)), is(t2)),
            isPair(isGeometry(nztmHelper.line(300, 150, 350, 150)), is(t3))
        )
    );
  }

  @Test
  public void lineIntersectingWithPointyRelation() {
    // a line can intersect with a point relation. In which case the intersections are points
    assertThat(pointySubject.evaluateIntersection(nztmHelper.line(50, 100, 300, 100)),
        containsInAnyOrder(
            isPair(isGeometry(pt1.fetch("geom")), is(pt1)), // line goes through
            isPair(isGeometry(pt2.fetch("geom")), is(pt2)), // line goes through
            isPair(isGeometry(pt3.fetch("geom")), is(pt3))  // line touches
        )
    );
  }

  @Test
  public void boxIntersectingWithPointyRelation() {
    // a polygon can intersect with a point relation. In which case the intersections are points
    assertThat(pointySubject.evaluateIntersection(nztmHelper.box(50, 50, 200, 150)),
        containsInAnyOrder(
            isPair(isGeometry(pt1.fetch("geom")), is(pt1)), // in box
            isPair(isGeometry(pt2.fetch("geom")), is(pt2))  // on box edge
        )
    );
  }

  @Test
  public void doesNotFindTouchingIntersections() {
    // an intersection that results in a different geom type should not be found. E.g. an edge of a
    // polygon that touches a hazard but doesn't cross over it.

    // a box that is on the boundary
    assertThat(subject.evaluateIntersection(nztmHelper.box(100, 200, 300, 200)), hasSize(0));

    // a line whose end touches the boundary
    assertThat(subject.evaluateIntersection(nztmHelper.line(150, 200, 150, 300)), hasSize(0));
  }

  @Test
  public void intersectionsCanResultInMultiGeometry() {
    Polygon forkedTongue = nztmHelper.box(
        nztmHelper.toCoordinate(130, 190),
        nztmHelper.toCoordinate(150, 210),
        nztmHelper.toCoordinate(170, 190),
        nztmHelper.toCoordinate(170, 220),
        nztmHelper.toCoordinate(130, 220),
        nztmHelper.toCoordinate(130, 190)
    );

    Polygon fork1 = nztmHelper.box(
        nztmHelper.toCoordinate(130, 190),
        nztmHelper.toCoordinate(140, 200),
        nztmHelper.toCoordinate(130, 200),
        nztmHelper.toCoordinate(130, 190)
    );

    Polygon fork2 = nztmHelper.box(
        nztmHelper.toCoordinate(170, 190),
        nztmHelper.toCoordinate(170, 200),
        nztmHelper.toCoordinate(160, 200),
        nztmHelper.toCoordinate(170, 190)
    );

    List<Pair<Geometry, Object>> found = subject.evaluateIntersection(forkedTongue);
    assertThat(found, hasSize(1));
    assertThat(found.get(0).getRight(), is(t1));
    List<Geometry> parts = new ArrayList<>();
    GeometryUtils.processPerPart(found.get(0).getLeft(), part -> parts.add(part));
    assertThat(parts, containsInAnyOrder(
        geometryTopoMatch(fork1),
        geometryTopoMatch(fork2)
    ));
  }

  @Test
  public void findAllIntersectionLinesFromOtherCRS() {
    LineString nzLine = nztmHelper.line(150, 150, 350, 150);
    LineString latLongLine = (LineString) latLongHelper.reproject(nzLine);

    assertThat(nzLine, not(latLongLine));

    List<Pair<Geometry, Object>> result = subject.evaluateIntersection(latLongLine);
    assertThat(result, containsInAnyOrder(
        isPair(geometryMatch(
            latLongHelper.reproject(nztmHelper.line(150, 150, 200, 150)),
            DEGREE_TOLERANCE_NEAREST_CM),
            is(t1)),
        isPair(geometryMatch(
            latLongHelper.reproject(nztmHelper.line(200, 150, 300, 150)),
            DEGREE_TOLERANCE_NEAREST_CM),
            is(t2)),
        isPair(geometryMatch(
            latLongHelper.reproject(nztmHelper.line(300, 150, 350, 150)),
            DEGREE_TOLERANCE_NEAREST_CM),
            is(t3))
    ));
  }
}
