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

import org.junit.Before;
import org.junit.Test;

import nz.org.riskscape.engine.ArgsProblems;
import nz.org.riskscape.engine.Tuple;
import nz.org.riskscape.engine.data.ResolvedBookmark;
import nz.org.riskscape.engine.defaults.function.LookupBookmark;
import nz.org.riskscape.engine.function.IdentifiedFunction;
import nz.org.riskscape.engine.function.IdentifiedFunction.Category;
import nz.org.riskscape.engine.gt.GeometryHelper;
import nz.org.riskscape.engine.relation.ListRelation;
import nz.org.riskscape.engine.rl.BaseExpressionRealizerTest;
import nz.org.riskscape.engine.rl.DefaultOperators;
import nz.org.riskscape.engine.rl.RealizableFunction;
import nz.org.riskscape.engine.types.Nullable;
import nz.org.riskscape.engine.types.Referenced;
import nz.org.riskscape.engine.types.Struct;
import nz.org.riskscape.engine.types.Types;

@SuppressWarnings("unchecked")
public class SampleOneRealizationTest extends BaseExpressionRealizerTest {

  SampleClosest subject = new SampleClosest();
  GeometryHelper nzGeomHelper = GeometryHelper.nzMapGridWithOriginShift(project.getSridSet());
  GeometryHelper latLongGeomHelper = GeometryHelper.latLong(project.getSridSet());

  Struct sampleType = Struct.of("geom", Referenced.of(Types.POLYGON, nzGeomHelper.getCrs()), "value", Types.INTEGER);
  ResolvedBookmark polygonBookmark;

  Tuple s1 = Tuple.ofValues(sampleType, nzGeomHelper.box(100, 100, 150, 150), 10L);
  Tuple s2 = Tuple.ofValues(sampleType, nzGeomHelper.box(150, 150, 200, 200), 20L);
  Tuple s3 = Tuple.ofValues(sampleType, nzGeomHelper.box(200, 100, 250, 150), 30L);
  Tuple s4 = Tuple.ofValues(sampleType, nzGeomHelper.box(250, 150, 300, 200), 40L);
  Tuple s5 = Tuple.ofValues(sampleType, nzGeomHelper.box(250, 450, 350, 550), 40L);

  public SampleOneRealizationTest() {
    project.getFunctionSet().insertFirst(DefaultOperators.INSTANCE);
    project.getFunctionSet().add(subject.builtin("sample_one", Category.GEOMETRY_PROCESSING), DEFAULTS_SOURCE);

    project.getFunctionSet().add(new ToTypedCoverage()
        .builtin("to_coverage", Category.MISC), DEFAULTS_SOURCE);

    LookupBookmark lookupBookmark = new LookupBookmark();
    project.getFunctionSet().add(
        RealizableFunction.asFunction(lookupBookmark, lookupBookmark.getArguments(), Types.ANYTHING)
            .builtin("bookmark", IdentifiedFunction.Category.MISC));
  }

  @Before
  public void setupData() {
    polygonBookmark = addPickledData("polygons", new ListRelation(sampleType,
        s1, s2, s3, s4
    ));
  }

  @Test
  public void findsSampleAtCentre() {
    Struct inputType = Struct.of("geom", Types.GEOMETRY, "value", Types.FLOATING);

    assertThat(evaluate("sample_one(geom, to_coverage(bookmark('polygons')), buffer-distance: 0.0)",
        Tuple.ofValues(inputType, nzGeomHelper.point(125, 125))),
        is(s1)
    );

    assertThat(evaluate("sample_one(geom, to_coverage(bookmark('polygons')), buffer-distance: 0.0)",
        Tuple.ofValues(inputType, nzGeomHelper.point(150, 150))),
        oneOf(s1, s2)
    );

    assertThat(evaluate("sample_one(geom, to_coverage(bookmark('polygons')), buffer-distance: 0.0)",
        Tuple.ofValues(inputType,  nzGeomHelper.box(-20, -20, 200, 200))),
        is(s1)
    );
  }

  @Test
  public void findsSampleClosestToCentre() {
    // when the geom does not have a match at the center, but covers many, then the match closed to the centroid
    // should win
    Struct inputType = Struct.of("geom", Types.GEOMETRY, "value", Types.FLOATING);

    assertThat(evaluate("sample_one(geom, to_coverage(bookmark('polygons')), buffer-distance: 0.0)",
        Tuple.ofValues(inputType,  nzGeomHelper.box(0, 0, 440, 440))),
        is(s2)  // s5 if very near the centre, but not as close to the edge as s2.
    );
  }

  @Test
  public void findsSampleClosestToOrigGeomWhenBuffering() {
    // when the geom does not have a match at the center, but covers many, then the match closed to the centroid
    // should win
    Struct inputType = Struct.of("geom", Types.GEOMETRY, "value", Types.FLOATING);

    assertThat(evaluate("sample_one(geom, to_coverage(bookmark('polygons')), buffer-distance: 30.0)",
        Tuple.ofValues(inputType,  nzGeomHelper.box(150, 220, 200, 800))),
        is(s2)
    );
  }

  @Test
  public void findsSampleAtCentreOfStructWithGeomNoOptionalBuffer() {
    Struct exposureType = Struct.of("geom", Types.GEOMETRY, "value", Types.FLOATING);
    Struct inputType = Struct.of("value", exposureType);

    assertThat(evaluate("sample_one(value, to_coverage(bookmark('polygons')))",
        Tuple.ofValues(inputType, Tuple.ofValues(exposureType, nzGeomHelper.point(125, 125)))),
        is(s1)
    );
  }

  @Test
  public void findsSampleAtCentreNoOptionalBuffer() {
    Struct inputType = Struct.of("geom", Types.GEOMETRY, "value", Types.FLOATING);

    assertThat(evaluate("sample_one(geom, to_coverage(bookmark('polygons')))",
        Tuple.ofValues(inputType, nzGeomHelper.point(125, 125))),
        is(s1)
    );

    assertThat(evaluate("sample_one(geom, to_coverage(bookmark('polygons')))",
        Tuple.ofValues(inputType, nzGeomHelper.point(150, 150))),
        oneOf(s1, s2)
    );
  }

  @Test
  public void findsSampleWithinBuffer() {
    Struct inputType = Struct.of("geom", Types.GEOMETRY, "value", Types.FLOATING);

    assertThat(evaluate("sample_one(geom, to_coverage(bookmark('polygons')), buffer-distance: 15.0)",
        Tuple.ofValues(inputType, nzGeomHelper.point(125, 90))),
        is(s1)
    );

    // equal distance from these three points, but one of them wins (first returned from coverage)
    assertThat(evaluate("sample_one(geom, to_coverage(bookmark('polygons')), buffer-distance: 30.0)",
        Tuple.ofValues(inputType, nzGeomHelper.point(175, 175))),
        oneOf(s1, s2, s3)
    );

    // move slightly closer to s2
    assertThat(evaluate("sample_one(geom, to_coverage(bookmark('polygons')), buffer-distance: 30.0)",
        Tuple.ofValues(inputType, nzGeomHelper.point(175, 180))),
        is(s2)
    );
  }

  @Test
  public void findsSampleWithinBufferFromContext() {
    Struct inputType = Struct.of("geom", Types.GEOMETRY, "value", Types.FLOATING);

    assertThat(evaluate("sample_one(geom, to_coverage(bookmark('polygons')), buffer-distance: value)",
        Tuple.ofValues(inputType, nzGeomHelper.point(125, 90), 15.0D)),
        is(s1)
    );

    // equal distance from these three points, but one of them wins (first returned from coverage)
    assertThat(evaluate("sample_one(geom, to_coverage(bookmark('polygons')), buffer-distance: value * 2)",
        Tuple.ofValues(inputType, nzGeomHelper.point(175, 175), 15.0D)),
        oneOf(s1, s2, s3)
    );

    // move slightly closer to s2
    assertThat(evaluate("sample_one(geom, to_coverage(bookmark('polygons')), buffer-distance: value + value)",
        Tuple.ofValues(inputType, nzGeomHelper.point(175, 180), 15.0D)),
        is(s2)
    );
  }

  @Test
  public void findsSampleWhenCalledWithComplexFunctionAdapting() {
    Struct childType = Struct.of("geom", Types.GEOMETRY, "value", Nullable.FLOATING);
    Struct inputType = Struct.of("value", Nullable.of(childType));

    assertThat(evaluate("sample_one(value, to_coverage(bookmark('polygons')))",
        Tuple.ofValues(inputType, Tuple.ofValues(childType, nzGeomHelper.point(125, 125), 15.0D))),
        is(s1)
    );
  }

  @Test
  public void willNoRealizeIfArgWrongType() {
    Struct exposureType = Struct.of("geom", Types.GEOMETRY, "value", Types.FLOATING);
    Struct inputType = Struct.of("value", exposureType);

    assertThat(
        realizeOnly("sample_one('foo', to_coverage(bookmark('polygons')), buffer-distance: value)", inputType),
        failedResult(hasAncestorProblem(
            is(ArgsProblems.mismatch(subject.getArguments().get(0), Types.TEXT))
        ))
    );

    assertThat(realizeOnly("sample_one(value, 'foo', buffer-distance: value)", inputType),
        failedResult(hasAncestorProblem(
            is(ArgsProblems.mismatch(subject.getArguments().get(1), Types.TEXT))
        ))
    );

    assertThat(
        realizeOnly("sample_one(value, to_coverage(bookmark('polygons')), buffer-distance: 'foo')", inputType),
        failedResult(hasAncestorProblem(
            is(ArgsProblems.mismatch(subject.getArguments().get(2), Types.TEXT))
        ))
    );

  }

}
