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

import org.junit.Test;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.Point;
import org.geotools.api.referencing.FactoryException;

import nz.org.riskscape.engine.ArgsProblems;
import nz.org.riskscape.engine.GeometryReprojectionException;
import nz.org.riskscape.engine.Matchers;
import nz.org.riskscape.engine.Tuple;
import nz.org.riskscape.engine.function.IdentifiedFunction;
import nz.org.riskscape.engine.gt.GeometryHelper;
import nz.org.riskscape.engine.rl.BaseExpressionRealizerTest;
import nz.org.riskscape.engine.rl.EvalException;
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 ReprojectTest extends BaseExpressionRealizerTest {

  Reproject subject = new Reproject();
  GeometryHelper latLongHelper = GeometryHelper.latLong(project.getSridSet());
  GeometryHelper nzHelper = GeometryHelper.nzMapGridWithOriginShift(project.getSridSet());

  Point nzPoint = nzHelper.point(1000, 1000);
  Point latLongPoint = (Point)latLongHelper.reproject(nzPoint);

  public ReprojectTest() {
    project.getFunctionSet().add(subject.builtin("reproject", IdentifiedFunction.Category.GEOMETRY_PROCESSING));
  }

  @Test
  public void canReprojectToEPSGCode() {
    Struct inputType = Struct.of("geom", Referenced.of(Types.POINT, latLongHelper.getCrs()),
        "crs", Nullable.TEXT);

    assertThat((Geometry)evaluate("reproject(geom, 'EPSG:27200')", Tuple.ofValues(inputType, latLongPoint)),
        geometryMatch(nzPoint, METER_TOLERANCE_NEAREST_CM));
    assertThat(realized.getResultType(), is(Referenced.of(Types.POINT, nzHelper.getCrs())));

    assertThat((Geometry)evaluate("reproject(geom, crs)", Tuple.ofValues(inputType, latLongPoint, "EPSG:27200")),
        geometryMatch(nzPoint, METER_TOLERANCE_NEAREST_CM));
    // note that the return type is not referenced. because we don't know what the target crs is when
    // realizing
    assertThat(realized.getResultType(), is(Nullable.of(Types.POINT)));
    assertThat(evaluate("reproject(geom, crs)", Tuple.ofValues(inputType, nzPoint)), nullValue());
  }

  @Test
  public void canReprojectToReferenced() {
    Struct inputType = Struct.of("geom", Referenced.of(Types.POINT, latLongHelper.getCrs()),
        "crs", Referenced.of(Types.POLYGON, nzHelper.getCrs()));

    assertThat((Geometry)evaluate("reproject(geom, 'EPSG:27200')", Tuple.ofValues(inputType, latLongPoint)),
        geometryMatch(nzPoint, METER_TOLERANCE_NEAREST_CM));
    assertThat(realized.getResultType(), is(Referenced.of(Types.POINT, nzHelper.getCrs())));
  }

  @Test
  public void canReprojectToAnotherGeometriesCRS() {
    Struct inputType = Struct.of("geom", Referenced.of(Types.POINT, latLongHelper.getCrs()),
        "crs", Types.POINT);

    assertThat((Geometry)evaluate("reproject(geom, crs)", Tuple.ofValues(inputType, latLongPoint, nzPoint)),
        geometryMatch(nzPoint, METER_TOLERANCE_NEAREST_CM));
    assertThat(realized.getResultType(), is(Types.POINT));
  }

  @Test
  public void failIfReprojectionNotPosible() {
    Struct inputType = Struct.of("geom", Referenced.of(Types.POINT, latLongHelper.getCrs()),
        "crs", Referenced.of(Types.POLYGON, nzHelper.getCrs()));

    EvalException ex = assertThrows(EvalException.class, () -> evaluate("reproject(geom, crs)",
        Tuple.ofValues(inputType, latLongHelper.point(10, 20))));
    assertThat(ex.getProblem(), Matchers.hasAncestorProblem(isProblem(GeometryReprojectionException.class)));
  }

  @Test
  public void failsIfCRSUnknown() {
    Struct inputType = Struct.of("geom", Referenced.of(Types.POINT, latLongHelper.getCrs()),
        "crs", Nullable.TEXT);

    // if the crs is constant then we will get the error at realization
    assertThat(realizeOnly("reproject(geom, 'EPSG:somewhere')", inputType), Matchers.failedResult(
        Matchers.hasAncestorProblem(Matchers.isProblem(FactoryException.class))
    ));

    // but if the crs is not contstant then it'll be an eval
    EvalException ex = assertThrows(EvalException.class,
        () -> evaluate("reproject(geom, crs)",
            Tuple.ofValues(inputType, latLongHelper.point(10, 10), "EPSG:somewhere")));
    assertThat(ex.getProblem(),
        Matchers.hasAncestorProblem(Matchers.isProblem(FactoryException.class))
    );
  }

  @Test
  public void failsIfArgsWrongTypes() {
    assertThat(realizeOnly("reproject('geom', 'EPSG:4326')", Struct.EMPTY_STRUCT), Matchers.failedResult(
        Matchers.hasAncestorProblem(is(ArgsProblems.mismatch(subject.getArguments().get(0), Types.TEXT)))
    ));

    assertThat(realizeOnly("reproject(geom, 12)", Struct.of("geom", Types.GEOMETRY)), Matchers.failedResult(
        Matchers.hasAncestorProblem(is(ArgsProblems.mismatch(subject.getArguments().get(1), Types.INTEGER)))
    ));
  }

  @Test
  public void failsIfWrongNumberOfArguments() {
    Struct inputType = Struct.of("geom", Referenced.of(Types.POINT, latLongHelper.getCrs()));
    assertThat(realizeOnly("reproject()", inputType), Matchers.failedResult(
        Matchers.hasAncestorProblem(is(ArgsProblems.get().wrongNumber(2, 0)))
    ));

    assertThat(realizeOnly("reproject(geom)", inputType), Matchers.failedResult(
        Matchers.hasAncestorProblem(is(ArgsProblems.get().wrongNumber(2, 1)))
    ));

    assertThat(realizeOnly("reproject(geom, 'EPSG:4326', 10)", inputType), Matchers.failedResult(
        Matchers.hasAncestorProblem(is(ArgsProblems.get().wrongNumber(2, 3)))
    ));
  }

}
