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

import static nz.org.riskscape.engine.Assert.*;
import static nz.org.riskscape.engine.geo.GeometryFixerTest.*;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;

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

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

import nz.org.riskscape.engine.GeometryProblems;
import nz.org.riskscape.engine.Matchers;
import nz.org.riskscape.engine.SRIDSet;
import nz.org.riskscape.engine.Tuple;
import nz.org.riskscape.engine.geo.GeometryValidation;
import nz.org.riskscape.engine.gt.GeometryHelper;
import nz.org.riskscape.engine.projection.ValidateGeometryProjection.ValidateGeometryProjector;
import nz.org.riskscape.engine.relation.InvalidTupleException;
import nz.org.riskscape.engine.types.Struct;
import nz.org.riskscape.engine.types.Struct.StructMember;
import nz.org.riskscape.engine.types.Types;
import nz.org.riskscape.problem.Problem;
import nz.org.riskscape.problem.Problem.Severity;

public class ValidateGeometryProjectionTest {

  SRIDSet sridSet = new SRIDSet();
  GeometryHelper helper = GeometryHelper.nzTransverseMercatorWithOriginShift(sridSet);

  Struct type = Struct.of("geom", Types.GEOMETRY);
  StructMember geomMember = type.getEntry("geom");

  List<Problem> problems = new ArrayList<>();
  Object context = new Object();

  ValidateGeometryProjection validatingProjection = new ValidateGeometryProjection(GeometryValidation.ERROR,
      context, p -> problems.add(p));
  ValidateGeometryProjector validatingProjector =
      (ValidateGeometryProjector)validatingProjection.getProjectionFunction(type).get();

  Geometry validBox = helper.box(100, 100, 200, 200);

  @Test
  public void doesNotChangeValidGeometry() {
    Geometry valid = helper.box(0, 0, 100, 100);
    Geometry projected = project(valid);
    assertSame(valid, projected);
  }

  @Test
  public void throwsInvalidTupleExForInvalidGeometry() {
    // Lets make sure it isn't valid
    assertFalse(INVALID_POINT_UNFIXABLE.isValid());

    InvalidTupleException ex = assertThrows(InvalidTupleException.class, () -> project(INVALID_POINT_UNFIXABLE));
    assertThat(ex.getReason(), Matchers.isProblem(Problem.Severity.ERROR, GeometryProblems.class, "invalid"));

    // you don't get a problem and an exception
    assertTrue(problems.isEmpty());
  }

  @Test
  public void willValidateAllGeometries() {
    Struct inputType = Struct.of("geom1", Types.POLYGON, "geom2", Types.GEOMETRY);

    ValidateGeometryProjection warningProjection = new ValidateGeometryProjection(GeometryValidation.ERROR,
      context, p -> problems.add(p));
    Projector warningProjector = warningProjection.getProjectionFunction(inputType).get();

    // valid input passes on through
    Tuple validInput = Tuple.ofValues(inputType, validBox, validBox);
    assertSame(validInput, warningProjector.apply(validInput));

    // invalid geometries will be fixed (if they can be)
    Tuple fixalbeInput = Tuple.ofValues(inputType, INVALID_BOWTIE, INVALID_BANANA);
    Tuple fixed = warningProjector.apply(fixalbeInput);
    assertTrue(((Geometry)fixed.fetch("geom1")).isValid());
    assertTrue(((Geometry)fixed.fetch("geom2")).isValid());
    // warning logs each invalid geom that is fixed
    assertThat(problems, contains(
        Matchers.hasAncestorProblem(Matchers.isProblem(Severity.WARNING, GeometryProblems.class, "fixedInvalid")),
        Matchers.hasAncestorProblem(Matchers.isProblem(Severity.WARNING, GeometryProblems.class, "fixedInvalid"))
    ));

    // checks the first geometry
    InvalidTupleException ex = assertThrows(InvalidTupleException.class,
        () -> warningProjector.apply(Tuple.ofValues(inputType, INVALID_POINT_UNFIXABLE, validBox)));
    assertThat(ex.getReason(), Matchers.isProblem(Problem.Severity.ERROR, GeometryProblems.class, "invalid"));

    // checks the second geometry
    ex = assertThrows(InvalidTupleException.class,
        () -> warningProjector.apply(Tuple.ofValues(inputType, validBox, INVALID_POINT_UNFIXABLE)));
    assertThat(ex.getReason(), Matchers.isProblem(Problem.Severity.ERROR, GeometryProblems.class, "invalid"));
  }

  @Test
  public void willWarnOnAnyInvalidGeometry() {
    Struct inputType = Struct.of("geom1", Types.POLYGON, "geom2", Types.GEOMETRY);

    // we only want to be warned about invalid geometries, but carry on regardless
    ValidateGeometryProjection warningProjection = new ValidateGeometryProjection(GeometryValidation.WARN,
      context, p -> problems.add(p));
    Projector warningProjector = warningProjection.getProjectionFunction(inputType).get();

    // valid input passes on through
    Tuple validInput = Tuple.ofValues(inputType, validBox, validBox);
    assertSame(validInput, warningProjector.apply(validInput));

    // invalid geometries will be fixed (if they can be)
    Tuple fixalbeInput = Tuple.ofValues(inputType, INVALID_BOWTIE, INVALID_BANANA);
    Tuple fixed = warningProjector.apply(fixalbeInput);
    assertTrue(((Geometry)fixed.fetch("geom1")).isValid());
    assertTrue(((Geometry)fixed.fetch("geom2")).isValid());
    // warning logs each invalid geom that is fixed
    assertThat(problems, contains(
        Matchers.hasAncestorProblem(Matchers.isProblem(Severity.WARNING, GeometryProblems.class, "fixedInvalid")),
        Matchers.hasAncestorProblem(Matchers.isProblem(Severity.WARNING, GeometryProblems.class, "fixedInvalid"))
    ));

    // checks the first geometry
    problems.clear();
    warningProjector.apply(Tuple.ofValues(inputType, INVALID_POINT_UNFIXABLE, validBox));
    assertThat(problems, contains(Matchers.hasAncestorProblem(
        Matchers.isProblem(Problem.Severity.WARNING, GeometryProblems.class, "invalid"))
    ));

    problems.clear();

    // checks the second geometry
    warningProjector.apply(Tuple.ofValues(inputType, validBox, INVALID_POINT_UNFIXABLE));
    assertThat(problems, contains(Matchers.hasAncestorProblem(
        Matchers.isProblem(Problem.Severity.WARNING, GeometryProblems.class, "invalid"))
    ));
  }

  @Test
  public void noGeometyIsNoProblem() {
    // if there is no geometry to validate we get an identity projection effect
    Struct inputType = Struct.of("value", Types.TEXT);
    ValidateGeometryProjection myProjection = new ValidateGeometryProjection(GeometryValidation.WARN,
        context, p -> problems.add(p));
    Projector nonValidatingProjector = myProjection.getProjectionFunction(inputType).get();

    Tuple input = Tuple.ofValues(inputType, "foo");
    assertSame(input, nonValidatingProjector.apply(input));
  }

  @Test
  public void noProblemIfModeIsOff() {
    ValidateGeometryProjection nonValidatingProjection = new ValidateGeometryProjection(GeometryValidation.OFF,
        context, p -> problems.add(p));
    Projector nonValidatingProjector = nonValidatingProjection.getProjectionFunction(type).get();

    Tuple invalidTuple = Tuple.ofValues(type, INVALID_POINT_UNFIXABLE);
    assertSame(invalidTuple, nonValidatingProjector.apply(invalidTuple));
  }

  private Geometry project(Geometry geom) {
    return validatingProjector.apply(Tuple.ofValues(type, geom)).fetch(geomMember);
  }

}
