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

import static org.hamcrest.Matchers.*;

import org.junit.Test;

import static org.junit.Assert.*;
import static org.mockito.Mockito.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.function.Function;

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 org.mockito.Mockito;

import com.google.common.collect.Lists;

import nz.org.riskscape.engine.geo.GeometryUtils;
import nz.org.riskscape.engine.types.CoverageType;
import nz.org.riskscape.engine.types.Types;
import nz.org.riskscape.engine.util.Pair;

public class SampleClosestTest extends BaseSampleCoverageTest {

  public SampleClosestTest() {
    function = new SampleClosest();
  }

  @Test
  public void willReturnCentroidMatchFirst() throws Exception {
    Polygon boxCentredAtPoint1 = geomHelper.box(0, 1, 2, 3);
    when(coverage.evaluate(Mockito.eq(point1))).thenReturn("you got it");
    realize();
    assertEquals("you got it", realized.call(Arrays.asList(boxCentredAtPoint1, coverage)));

    verify(coverage, never()).getEvaluateIntersectionOp();
  }

  @Test
  public void willReturnCentroidMatchFirstForStraightLine() throws Exception {
    // the centroid of a straight line should be contained by the line, so a centroid match should win.
    LineString straightLine = geomHelper.line(0, 0, 0, 100);
    when(coverage.evaluate(Mockito.eq(straightLine.getCentroid()))).thenReturn("you got it");
    realize();
    assertEquals("you got it", realized.call(Arrays.asList(straightLine, coverage)));

    verify(coverage, never()).getEvaluateIntersectionOp();
  }

  @Test
  public void willReturnMidPointMatchFirstForNonStraightLine() throws Exception {
    LineString cShape = geomHelper.line(
        geomHelper.toCoordinate(100, 100),
        geomHelper.toCoordinate(0, 100),
        geomHelper.toCoordinate(0, 0),
        geomHelper.toCoordinate(100, 0)
    );
    when(coverage.evaluate(Mockito.eq(GeometryUtils.getMidpoint(cShape).get()))).thenReturn("you got it");
    realize();
    assertEquals("you got it", realized.call(Arrays.asList(cShape, coverage)));

    verify(coverage, never()).getEvaluateIntersectionOp();
  }

  @Test
  public void willReturnClosestAllIntersectionMatch() throws Exception {
    Polygon circle = (Polygon) point1.buffer(1);
    when(coverage.evaluate(Mockito.eq(point1))).thenReturn(null);

    List<Geometry> sampled = new ArrayList<>();
    Function<Geometry, List<Pair<Geometry, Object>>> op = geom -> {
      sampled.add(geom);
      return Lists.newArrayList(
          Pair.<Geometry, Object>of(geomHelper.point(10, 10), "far away"),
          Pair.<Geometry, Object>of(point2, "found it")
      );
    };
    when(coverage.getEvaluateIntersectionOp()).thenReturn(Optional.of(op));
    realize();

    assertEquals("found it", realized.call(Arrays.asList(circle, coverage)));
  }

  @Test
  public void willNotEvaluateIntersectionsForMissingPoint() throws Exception {
    Point point = geomHelper.point(1000, 1000);
    when(coverage.evaluate(Mockito.eq(point))).thenReturn(null);
    Function<Geometry, List<Pair<Geometry, Object>>> op = geom -> {
      if (true) {
        // we need to supply the intersection op. but it should not be used
        throw new RuntimeException("should not be called");
      }
      List<Pair<Geometry, Object>> results = new ArrayList<>();
      return results;
    };
    when(coverage.getEvaluateIntersectionOp()).thenReturn(Optional.of(op));
    realize();
    assertNull(realized.call(Arrays.asList(point, coverage)));
  }

  @Test
  public void willBufferPointIfNotFoundAtCentroid() throws Exception {
    Point point = geomHelper.point(1000, 1000);
    when(coverage.evaluate(Mockito.eq(point))).thenReturn(null);
    List<Geometry> sampled = new ArrayList<>();
    Function<Geometry, List<Pair<Geometry, Object>>> op = geom -> {
      sampled.add(geom);
      return Lists.newArrayList(
          Pair.<Geometry, Object>of(geomHelper.point(1000, 1010), "found it")
      );
    };
    when(coverage.getEvaluateIntersectionOp()).thenReturn(Optional.of(op));
    realizeBuffered();
    assertEquals("found it", realized.call(Arrays.asList(point, coverage, 100D)));
    assertThat(sampled, contains(is(point.buffer(100))));
  }

  @Test
  public void willNotSampleCentroidIfThatOutsideOfGeometry() throws Exception {
    Geometry cShape = geomHelper.line(
        geomHelper.toCoordinate(100, 100),
        geomHelper.toCoordinate(0, 100),
        geomHelper.toCoordinate(0, 0),
        geomHelper.toCoordinate(100, 0)
    ).buffer(1);
    // sanity check that for this shape the centroid is not within it.
    assertFalse(cShape.contains(cShape.getCentroid()));

    List<Geometry> sampled = new ArrayList<>();
    Function<Geometry, List<Pair<Geometry, Object>>> op = geom -> {
      sampled.add(geom);
      return Lists.newArrayList(
          Pair.<Geometry, Object>of(point2, "found it")
      );
    };
    when(coverage.getEvaluateIntersectionOp()).thenReturn(Optional.of(op));
    realize();

    assertEquals("found it", realized.call(Arrays.asList(cShape, coverage)));
    verify(coverage, never()).evaluate(any());
  }

  @Test
  public void willReturnClosestAllIntersectionMatchEvenWhenBuffering() throws Exception {
    // When buffering is turned on, we could have the case that a sample exists inside the original
    // geom, which is further away from the centroid than a sample in the buffer zone. For instance if
    // geom is a long rectangle.
    Polygon circle = (Polygon) point1.buffer(1);
    when(coverage.evaluate(Mockito.eq(point1))).thenReturn(null);

    List<Geometry> sampled = new ArrayList<>();
    Function<Geometry, List<Pair<Geometry, Object>>> op = geom -> {
      sampled.add(geom);
      return Lists.newArrayList(
          Pair.<Geometry, Object>of(geomHelper.point(10, 10), "far away"),
          Pair.<Geometry, Object>of(point2, "found it")
      );
    };
    when(coverage.getEvaluateIntersectionOp()).thenReturn(Optional.of(op));
    realizeBuffered();

    assertEquals("found it", realized.call(Arrays.asList(circle, coverage, 10.0D)));

    // confirm the the intersection function was called the expected times, with expected geometries
    assertThat(sampled, contains(
        circle
    ));
  }

  @Test
  public void willReturnClosestAllIntersectionBufferedMatchEvenWhenBuffering() throws Exception {
    // When buffering is turned on, we could have the case that a sample exists inside the original
    // geom, which is further away from the centroid than a sample in the buffer zone. For instance if
    // geom is a long rectangle.
    Polygon circle = (Polygon) point1.buffer(1);
    when(coverage.evaluate(Mockito.eq(point1))).thenReturn(null);

    List<Geometry> sampled = new ArrayList<>();
    Function<Geometry, List<Pair<Geometry, Object>>> op = geom -> {
      sampled.add(geom);
      if (geom.equals(circle)) {
        // no intersections for circle
        return Collections.emptyList();
      }
      // else if must be the buffered circle
      return Lists.newArrayList(
          Pair.<Geometry, Object>of(geomHelper.point(100, 100), "far far away"),
          Pair.<Geometry, Object>of(geomHelper.point(10, 10), "far away")
      );
    };
    when(coverage.getEvaluateIntersectionOp()).thenReturn(Optional.of(op));
    realizeBuffered();

    assertEquals("far away", realized.call(Arrays.asList(circle, coverage, 10.0D)));

    // confirm the the intersection function was called the expected times, with expected geometries
    assertThat(sampled, contains(
        circle,
        circle.buffer(10.0D)
    ));
  }

  protected void realizeBuffered() {
    realize(Types.GEOMETRY, new CoverageType(coverageMemberType), Types.FLOATING);
  }

}
