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

import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;

import org.junit.Test;
import org.locationtech.jts.geom.Envelope;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.Point;

import nz.org.riskscape.engine.SRIDSet;
import nz.org.riskscape.engine.Tuple;
import nz.org.riskscape.engine.gt.GeometryHelper;
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.problem.ProblemException;

public class NearestNeighbourIndexTest {

  SRIDSet sridSet = new SRIDSet();
  GeometryHelper nzmgGeometryHeper = GeometryHelper.nzMapGridWithOriginShift(sridSet);
  GeometryHelper latLongGeometryHeper = GeometryHelper.latLong(sridSet);
  GeometryHelper newYorkGeometryHeper = GeometryHelper.newYorkFoot(sridSet);

  Struct relationType = Struct.of("geom", Nullable.GEOMETRY, "value", Types.INTEGER);
  Struct.StructMember geomMember = relationType.getEntry("geom");

  Tuple nzP1 = Tuple.ofValues(relationType, nzmgGeometryHeper.point(1000, 1000), 1L);
  Tuple nzP2 = Tuple.ofValues(relationType, nzmgGeometryHeper.point(2000, 1000), 1L);
  Tuple nzP3 = Tuple.ofValues(relationType, nzmgGeometryHeper.point(2000, 2000), 1L);
  Tuple nzP4 = Tuple.ofValues(relationType, nzmgGeometryHeper.point(2000, 1800), 1L);

  Tuple latLongP1 = Tuple.ofValues(relationType,
      latLongGeometryHeper.reproject(nzmgGeometryHeper.point(1000, 1000)), 1L);
  Tuple latLongP2 = Tuple.ofValues(relationType,
      latLongGeometryHeper.reproject(nzmgGeometryHeper.point(2000, 1000)), 1L);
  Tuple latLongP3 = Tuple.ofValues(relationType,
      latLongGeometryHeper.reproject(nzmgGeometryHeper.point(2000, 2000)), 1L);
  Tuple latLongP4 = Tuple.ofValues(relationType,
      latLongGeometryHeper.reproject(nzmgGeometryHeper.point(2000, 1800)), 1L);

  Tuple newYorkP1 = Tuple.ofValues(relationType,
      newYorkGeometryHeper.point(1000, 1000), 1L);

  NearestNeighbourIndex subject;

  public void setupNZIndex() throws ProblemException {
    subject = NearestNeighbourIndex.metricMaxDistance(geomMember, sridSet, nzmgGeometryHeper.getCrs(), 100);
    subject.insert(nzP1);
    subject.insert(nzP2);
    subject.insert(nzP3);
    subject.insert(nzP4);
  }

  public void setupLatLongIndex() throws ProblemException {
    subject = NearestNeighbourIndex.metricMaxDistance(geomMember, sridSet, latLongGeometryHeper.getCrs(), 100);
    subject.insert(latLongP1);
    subject.insert(latLongP2);
    subject.insert(latLongP3);
    subject.insert(latLongP4);
  }

  public void setupNewYorkIndex() throws ProblemException {
    subject = NearestNeighbourIndex.metricMaxDistance(geomMember, sridSet, newYorkGeometryHeper.getCrs(), 100);
    subject.insert(newYorkP1);
  }

  @Test
  public void envelopeContainsAllPointsAndMaxDistance() throws ProblemException {
    setupNZIndex();
    Point lowerLeft = nzmgGeometryHeper.point(900, 900);
    Point upperRight = nzmgGeometryHeper.point(2100, 2100);
    assertThat(subject.getEnvelope(), is(new Envelope(lowerLeft.getX(), upperRight.getX(),
        lowerLeft.getY(), upperRight.getY())));
  }

  @Test
  public void findsClosestMatchWithinRange() throws ProblemException {
    setupNZIndex();
    assertThat(query(nzmgGeometryHeper.point(900, 1000)), is(nzP1));
    assertThat(query(nzmgGeometryHeper.point(1000, 1000)), is(nzP1));
    assertThat(query(nzmgGeometryHeper.point(1100, 1000)), is(nzP1));


    assertThat(query(nzmgGeometryHeper.point(2000, 1900)), oneOf(nzP3, nzP4));
    assertThat(query(nzmgGeometryHeper.point(2000, 1901)), is(nzP3));

    // no points in range in middle
    assertNull(query(nzmgGeometryHeper.point(1500, 1500)));

    // outside the envelope
    assertNull(query(nzmgGeometryHeper.point(2500, 2500)));
  }

  @Test
  public void findsClosestMatchWithinRangeLatLong() throws ProblemException {
    setupLatLongIndex();
    assertThat(query(latLongGeometryHeper.reproject(nzmgGeometryHeper.point(1000, 1000))), is(latLongP1));

    // moving down from the point is mostly accurate with the re-projection
    assertThat(query(latLongGeometryHeper.reproject(nzmgGeometryHeper.point(1000, 901))), is(latLongP1));
    assertThat(query(latLongGeometryHeper.reproject(nzmgGeometryHeper.point(1000, 900))), nullValue());

    // moving across from the point isn't as accurate, the cutoff is about 75m here in NZ, this is
    // because we are converting a metric distance to degress (for the cutoff) which can't be acurate in
    // all directions at all locations.
    assertThat(query(latLongGeometryHeper.reproject(nzmgGeometryHeper.point(925, 1000))), is(latLongP1));
    assertThat(query(latLongGeometryHeper.reproject(nzmgGeometryHeper.point(924, 1000))), nullValue());
  }

  @Test
  public void findsClosestMatchWithinRangeNewYork() throws ProblemException {
    // Here we are checking that the 100m max distance is correct, even when working with a foot based CRS
    setupNewYorkIndex();
    assertThat(query(newYorkGeometryHeper.point(1000, 1000)), is(newYorkP1));
    assertThat(query(newYorkGeometryHeper.point(1000, 700)), is(newYorkP1));  // 300ft is < 100m
    assertThat(query(newYorkGeometryHeper.point(1000, 650)), nullValue());    // 350ft is > 100m
  }

  @Test
  public void nullGeometriesAreIgnored() throws ProblemException {
    setupNZIndex();
    // sanity check that index is good
    assertThat(query(nzmgGeometryHeper.point(900, 1000)), is(nzP1));

    // insert a tuple with a null geometry. Nothing bad should happen here.
    subject.insert(Tuple.ofValues(relationType, null, "no geom"));

    // now we make sure the index still returns good values
    assertThat(query(nzmgGeometryHeper.point(900, 1000)), is(nzP1));
  }

  private Tuple query(Geometry geom) {
    return subject.query(geom.getCoordinate());
  }

}
