/*
 * 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.function.geometry.Buffer.*;
import static nz.org.riskscape.engine.GeoHelper.*;
import static nz.org.riskscape.engine.geo.GeometryUtils.*;

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

import org.junit.Before;
import org.junit.Test;
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 com.google.common.collect.Lists;

import nz.org.riskscape.engine.ArgsProblems;
import nz.org.riskscape.engine.Tuple;
import nz.org.riskscape.engine.gt.GeometryHelper;
import nz.org.riskscape.engine.problem.GeneralProblems;
import nz.org.riskscape.engine.rl.BaseExpressionRealizerTest;
import nz.org.riskscape.engine.rl.GeometryFunctions;
import nz.org.riskscape.engine.rl.LanguageFunctions;
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;
import nz.org.riskscape.rl.ast.ExpressionProblems;

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

  GeometryHelper latLongHelper = GeometryHelper.latLong(project.getSridSet());
  GeometryHelper nzGeomHelper = GeometryHelper.nzMapGridWithOriginShift(project.getSridSet());

  Struct type = Struct.of("geom", Types.GEOMETRY, "distance", Types.FLOATING, "nGeom", Nullable.GEOMETRY);

  Buffer subject = new Buffer();

  @Before
  public void setup() {
    GeometryFunctions geometryFunctions = new GeometryFunctions(engine);
    project.getFunctionSet().addAll(LanguageFunctions.FUNCTIONS);
    project.getFunctionSet().addAll(geometryFunctions.getPredicates());
    project.getFunctionSet().addAll(geometryFunctions.getFunctions());
  }

  @Test
  public void bufferWithDefaultsRoundsCorners() throws Exception {
    Geometry result = (Geometry) evaluate("buffer(geom, distance)",
        Tuple.ofValues(type, latLongHelper.point(1, 1), METRES_PER_DEGREE / 2));

    assertThat(result, instanceOf(Polygon.class));
    Point center = result.getCentroid();
    assertThat(center.getX(), closeTo(1.0D, 0.0001D));
    assertThat(center.getY(), closeTo(1.0D, 0.0001D));
    assertThat(realized.getResultType(), is(Types.GEOMETRY));

    // now test buffer on a polygon
    result = (Geometry) evaluate("buffer(geom, distance)",
        Tuple.ofValues(type, latLongHelper.box(1, 1, 2, 2), METRES_PER_DEGREE / 2));

    assertThat(result, instanceOf(Polygon.class));
    // and now we can test the area of the buffered geom. So why isn't it 4 units squared.
    // The sides of the polygon will be pushed out by 0.5 but the corners will be radiused so that the perimeter
    // of new geom is never more than 0.5 away from the original geom.
    assertThat(result.getArea(), closeTo(3.780D, 0.001D));
    center = result.getCentroid();
    assertThat(center.getX(), closeTo(1.5D, 0.0001D));
    assertThat(center.getY(), closeTo(1.5D, 0.0001D));
    assertThat(realized.getResultType(), is(Types.GEOMETRY));
  }

  @Test
  public void canBufferRoundWhichIsSameAsDefault() {
    LineString line= nzGeomHelper.line(
        nzGeomHelper.toCoordinate(100, 200),
        nzGeomHelper.toCoordinate(100, 100),
        nzGeomHelper.toCoordinate(200, 100)
    );

    assertThat((Geometry)evaluate("buffer(geom, distance, {cap: 'round', vertex: 'round'})",
        Tuple.ofValues(type, line,  1)),
        geometryTopoMatch(line.buffer(1))
    );

    assertThat((Geometry)evaluate("buffer(geom, distance)",
        Tuple.ofValues(type, line,  1)),
        geometryTopoMatch(line.buffer(1))
    );
  }

  @Test
  public void canBufferALineSoItHasSquareCornersAndDoesGrowLonger() {
    // cap affects the what happens at the ends of a line.
    // a square cap will make the line longer by adding `distance` to each end, but the the ends will
    // be square (not rounded off)
    assertThat((Geometry)evaluate("buffer(geom, distance, {cap: 'square'})",
        Tuple.ofValues(type, nzGeomHelper.line(10, 10, 20, 10),  1)),
        geometryTopoMatch(nzGeomHelper.box(9, 9, 21, 11))
    );
    assertThat(realized.getResultType(), is(Types.GEOMETRY));

    assertThat((Geometry)evaluate("buffer(geom, distance: distance, options: {cap: 'square'})",
        Tuple.ofValues(type, nzGeomHelper.line(10, 10, 20, 10),  1)),
        geometryTopoMatch(nzGeomHelper.box(9, 9, 21, 11))
    );

    assertThat((Geometry)evaluate("buffer(geom, options: {cap: 'square'}, distance: distance)",
        Tuple.ofValues(type, nzGeomHelper.line(10, 10, 20, 10),  1)),
        geometryTopoMatch(nzGeomHelper.box(9, 9, 21, 11))
    );
  }

  @Test
  public void canBufferALineSoItHasSquareCornersAndDoesNotGrowLonger() {
    // cap affects the what happens at the ends of a line.
    // a flat cap prevents the line from growing longer. You could think of it as buffering along the
    // length only. The end is square.
    assertThat((Geometry)evaluate("buffer(geom, distance: distance, options: {cap: 'flat'})",
        Tuple.ofValues(type, nzGeomHelper.line(10, 10, 20, 10),  1)),
        geometryTopoMatch(nzGeomHelper.box(10, 9, 20, 11))
    );

    assertThat((Geometry)evaluate("buffer(geom, options: {cap: 'flat'}, distance: distance)",
        Tuple.ofValues(type, nzGeomHelper.line(10, 10, 20, 10),  1)),
        geometryTopoMatch(nzGeomHelper.box(10, 9, 20, 11))
    );
  }

  @Test
  public void returnsNullWhenArgsAreNull() {
    assertThat((Geometry)evaluate("buffer(nGeom, distance: distance, options: {cap: 'flat'})",
        Tuple.ofValues(type, nzGeomHelper.point(1, 1),  1, nzGeomHelper.line(10, 10, 20, 10))),
        geometryTopoMatch(nzGeomHelper.box(10, 9, 20, 11))
    );
    assertThat(realized.getResultType(), is(Nullable.GEOMETRY));

    // null geometry
    assertThat((Geometry)evaluate("buffer(nGeom, distance: distance, options: {cap: 'flat'})",
        Tuple.ofValues(type, nzGeomHelper.point(1, 1),  1)),
        nullValue()
    );
    assertThat(realized.getResultType(), is(Nullable.GEOMETRY));

    // null distance
    assertThat((Geometry)evaluate("buffer(geom, distance: null_of('floating'), options: {cap: 'flat'})",
        Tuple.ofValues(type, nzGeomHelper.point(1, 1),  1)),
        nullValue()
    );
    assertThat(realized.getResultType(), is(Nullable.GEOMETRY));

    Struct inputType = Struct.of("value", Nullable.of(type));
    assertThat((Geometry)evaluate("buffer(value, distance: 1, options: {cap: 'flat'})",
        Tuple.ofValues(inputType, Tuple.ofValues(type, nzGeomHelper.line(10, 10, 20, 10),  1))),
        geometryTopoMatch(nzGeomHelper.box(10, 9, 20, 11))
    );
    assertThat(realized.getResultType(), is(Nullable.GEOMETRY));

    assertThat((Geometry)evaluate("buffer(value, distance: 1, options: {cap: 'flat'})",
        Tuple.ofValues(inputType)),
        nullValue()
    );
    assertThat(realized.getResultType(), is(Nullable.GEOMETRY));
  }

  @Test
  public void canMitreCorners() {
    // join style affects what happens are exterior vertexes (or corners)
    // mitre will keep the same shape at the original. You could think if this as getting planks of
    // wood that is `distance` thick and using a mitre saw to cut it into bits that pack out the shape.
    LineString line= nzGeomHelper.line(
        nzGeomHelper.toCoordinate(100, 200),
        nzGeomHelper.toCoordinate(100, 100),
        nzGeomHelper.toCoordinate(200, 100)
    );

    assertThat((Geometry) evaluate("buffer(geom, distance: distance, options: {vertex: 'mitre', cap: 'square'})",
        Tuple.ofValues(type, line, 1)),
        geometryTopoMatch(nzGeomHelper.box(
            nzGeomHelper.toCoordinate(99, 201),
            nzGeomHelper.toCoordinate(99, 99),
            nzGeomHelper.toCoordinate(201, 99),
            nzGeomHelper.toCoordinate(201, 101),
            nzGeomHelper.toCoordinate(101, 101),
            nzGeomHelper.toCoordinate(101, 201),
            nzGeomHelper.toCoordinate(99, 201)
        ))
    );

    assertThat((Geometry) evaluate("buffer(geom, distance: distance, options: {vertex: 'mitre', cap: 'flat'})",
        Tuple.ofValues(type, line, 1)),
        geometryTopoMatch(nzGeomHelper.box(
            nzGeomHelper.toCoordinate(99, 200),
            nzGeomHelper.toCoordinate(99, 99),
            nzGeomHelper.toCoordinate(200, 99),
            nzGeomHelper.toCoordinate(200, 101),
            nzGeomHelper.toCoordinate(101, 101),
            nzGeomHelper.toCoordinate(101, 200),
            nzGeomHelper.toCoordinate(99, 200)
        ))
    );
  }

  @Test
  public void canBevelCorners() {
    // vertex style affects what happens are exterior vertexes (or corners)
    // bevel is a middle ground between round and mitre. for what it looks like start off my thinking
    // of mitre, then you pull out your wood plane and use it to take off the sharp corner.
    // so if you started off with a 90 degree corner, you would end up with two 45 degree corners.
    LineString line= nzGeomHelper.line(
        nzGeomHelper.toCoordinate(100, 200),
        nzGeomHelper.toCoordinate(100, 100),
        nzGeomHelper.toCoordinate(200, 100)
    );

    assertThat((Geometry) evaluate("buffer(geom, distance: distance, options: {vertex: 'bevel', cap: 'flat'})",
        Tuple.ofValues(type, line, 2)),
        geometryTopoMatch(nzGeomHelper.box(
            nzGeomHelper.toCoordinate(98, 200),
            nzGeomHelper.toCoordinate(98, 100),    // exterior bevels
            nzGeomHelper.toCoordinate(100, 98),
            nzGeomHelper.toCoordinate(200, 98),
            nzGeomHelper.toCoordinate(200, 102),
            nzGeomHelper.toCoordinate(102, 102),
            nzGeomHelper.toCoordinate(102, 200),
            nzGeomHelper.toCoordinate(98, 200)
        ))
    );
  }

  @Test
  public void canMitreABox() {
    Polygon box = nzGeomHelper.box(100, 100, 200, 200);
    Polygon mitredBox = nzGeomHelper.box(99, 99, 201, 201);
    assertThat((Geometry) evaluate("buffer(geom, distance: distance, options: {vertex: 'mitre'})",
        Tuple.ofValues(type, box, 1)),
        geometryTopoMatch(mitredBox)
    );

    // these tests show that cap makes no difference to polygons, because cap is about line ends.
    assertThat((Geometry) evaluate("buffer(geom, distance: distance, options: {vertex: 'mitre', cap: 'round'})",
        Tuple.ofValues(type, box, 1)),
        geometryTopoMatch(mitredBox)
    );
    assertThat((Geometry) evaluate("buffer(geom, distance: distance, options: {vertex: 'mitre', cap: 'flat'})",
        Tuple.ofValues(type, box, 1)),
        geometryTopoMatch(mitredBox)
    );
    assertThat((Geometry) evaluate("buffer(geom, distance: distance, options: {vertex: 'mitre', cap: 'square'})",
        Tuple.ofValues(type, box, 1)),
        geometryTopoMatch(mitredBox)
    );
  }

  @Test
  public void canBevelABox() {
    Polygon box = nzGeomHelper.box(100, 100, 200, 200);
    Polygon beveledBox = nzGeomHelper.box(
        nzGeomHelper.toCoordinate(100, 98),
        nzGeomHelper.toCoordinate(200, 98),
        nzGeomHelper.toCoordinate(202, 100),
        nzGeomHelper.toCoordinate(202, 200),
        nzGeomHelper.toCoordinate(200, 202),
        nzGeomHelper.toCoordinate(100, 202),
        nzGeomHelper.toCoordinate(98, 200),
        nzGeomHelper.toCoordinate(98, 100),
        nzGeomHelper.toCoordinate(100, 98)
    );
    assertThat((Geometry) evaluate("buffer(geom, distance: distance, options: {vertex: 'bevel'})",
        Tuple.ofValues(type, box, 2)),
        geometryTopoMatch(beveledBox)
    );

    // these tests show that cap makes no difference to polygons, because cap is about line ends.
    assertThat((Geometry) evaluate("buffer(geom, distance: distance, options: {vertex: 'bevel', cap: 'round'})",
        Tuple.ofValues(type, box, 2)),
        geometryTopoMatch(beveledBox)
    );
    assertThat((Geometry) evaluate("buffer(geom, distance: distance, options: {vertex: 'bevel', cap: 'flat'})",
        Tuple.ofValues(type, box, 2)),
        geometryTopoMatch(beveledBox)
    );
    assertThat((Geometry) evaluate("buffer(geom, distance: distance, options: {vertex: 'bevel', cap: 'square'})",
        Tuple.ofValues(type, box, 2)),
        geometryTopoMatch(beveledBox)
    );
  }

  @Test
  public void bufferingPointsWithOptions() {
    // buffering options don't make a lot of sense with point geometries.
    // but its good to know what happens.
    Point point = nzGeomHelper.point(1, 1);

    // we get a circle
    doBufferPoint(point, "round", 3.121445D);
    // we get a square
    doBufferPoint(point, "square", 4D);

    // buffering a point with a flat cap makes it disappear.
    doBufferPointWithFlatCap(point);
  }

  private void doBufferPoint(Point point, String cap, double expectedArea) {
    for (String join : new String[]{"round", "mitre", "bevel"}) {
      String expr = String.format("buffer(geom, distance, {cap: '%s', vertex: '%s'})", cap, join);
      Geometry result = (Geometry) evaluate(expr,
          Tuple.ofValues(type, point, 1));

      assertThat(result, instanceOf(Polygon.class));
      Point center = result.getCentroid();
      assertThat(center.getX(), closeTo(point.getCoordinate().x, 0.0001D));
      assertThat(center.getY(), closeTo(point.getCoordinate().y, 0.0001D));
      assertThat(result.getArea(), closeTo(expectedArea, 0.001D));
      assertThat(realized.getResultType(), is(Types.GEOMETRY));
    }
  }

  private void doBufferPointWithFlatCap(Point point) {
    for (String join : new String[]{"round", "mitre", "bevel"}) {
      String expr = String.format("buffer(geom, distance, {cap: 'flat', vertex: '%s'})", join);
      Geometry result = (Geometry) evaluate(expr,
          Tuple.ofValues(type, point, 1));

      assertThat(result, instanceOf(Polygon.class));
      // flat cap is not good for points though.
      assertThat(result.isEmpty(), is(true));
    }
  }

  @Test
  public void multiGeomsMayDissolveWhenBuffered() {
    // this multiline becomes a single polygon when buffered
    assertThat((Geometry) evaluate("buffer(geom, distance, options: {cap: 'square', vertex: 'mitre'})",
        Tuple.ofValues(type, nzGeomHelper.multiLine(
            nzGeomHelper.line(100, 100, 150, 100),
            nzGeomHelper.line(151, 100, 200, 100)
        ), 1D)),
        allOf(
            geometryTopoMatch(nzGeomHelper.box(99, 99, 201, 101)),
            instanceOf(Polygon.class)
        ));

    // this multibox becomes a single polygon when buffered
    assertThat((Geometry) evaluate("buffer(geom, distance, options: {cap: 'square', vertex: 'mitre'})",
        Tuple.ofValues(type, nzGeomHelper.multiBox(
            nzGeomHelper.box(100, 100, 150, 200),
            nzGeomHelper.box(151, 100, 200, 200)
        ), 1D)),
        allOf(
            geometryTopoMatch(nzGeomHelper.box(99, 99, 201, 201)),
            instanceOf(Polygon.class)
        ));
  }

  @Test
  public void canBufferAReferencedPolygon() {
    Struct myType = Struct.of("geom", Referenced.of(Types.POLYGON, nzGeomHelper.getCrs()), "distance", Types.FLOATING);
    Polygon box = nzGeomHelper.box(100, 100, 200, 200);
    Polygon mitredBox = nzGeomHelper.box(99, 99, 201, 201);
    assertThat((Geometry) evaluate("buffer(geom, distance: distance, options: {vertex: 'mitre'})",
        Tuple.ofValues(myType, box, 1)),
        geometryTopoMatch(mitredBox)
    );
    assertThat(realized.getResultType().find(Referenced.class).get().getCrs(), is(nzGeomHelper.getCrs()));
  }

  @Test
  public void canBufferTupleThatContainsReferencedPolygon() {
    Struct myType = Struct.of("geom", Referenced.of(Types.POLYGON, nzGeomHelper.getCrs()), "distance", Types.FLOATING);
    Struct inputType = Struct.of("value", myType);

    Polygon box = nzGeomHelper.box(100, 100, 200, 200);
    Polygon mitredBox = nzGeomHelper.box(99, 99, 201, 201);
    assertThat((Geometry) evaluate("buffer(value, distance: value.distance, options: {vertex: 'mitre'})",
        Tuple.ofValues(inputType, Tuple.ofValues(myType, box, 1))),
        geometryTopoMatch(mitredBox)
    );
    assertThat(realized.getResultType().find(Referenced.class).get().getCrs(), is(nzGeomHelper.getCrs()));
  }

  public void aNegativeDistanceCanTurnPolygonsIntoLinesOrPoints() {
    // this test is here to show that buffer does not always result in a polygon.
    // this to ensure that the result type isn't changed to always be polygon
    assertThat((Geometry) evaluate("buffer(foo, distance)",
        Tuple.ofValues(type, nzGeomHelper.box(99, 99, 101, 101))),
        geometryTopoMatch(nzGeomHelper.point(100, 100)));
    assertThat(realized.getResultType(), is(Types.GEOMETRY));

    assertThat((Geometry) evaluate("buffer(foo, distance)",
        Tuple.ofValues(type, nzGeomHelper.box(99, 99, 111, 101))),
        geometryTopoMatch(nzGeomHelper.line(100, 100, 110, 100)));
    assertThat(realized.getResultType(), is(Types.GEOMETRY));
  }

  @Test
  public void failsToRealizeIfArg1NotGeometry() {
    assertThat(realizeOnly("buffer(geom, value)", Struct.of("geom", Types.TEXT, "value", Types.FLOATING)),
        failedResult(hasAncestorProblem(is(ArgsProblems.mismatch(subject.getArguments().get(0), Types.TEXT)))));
  }

  @Test
  public void failsToRealizeIfArg2NotNumeric() {
    assertThat(realizeOnly("buffer(geom, value)", Struct.of("geom", Types.GEOMETRY, "value", Types.TEXT)),
        failedResult(hasAncestorProblem(is(ArgsProblems.mismatch(subject.getArguments().get(1), Types.TEXT)))));
  }

  @Test
  public void failsToRealizeIfTooManyArgs() {
    assertThat(realizeOnly("buffer(geom, value, value, value)",
        Struct.of("geom", Types.GEOMETRY, "value", Types.TEXT)),
        failedResult(hasAncestorProblem(is(ArgsProblems.get().wrongNumberRange(2, 3, 4)))));
  }

  @Test
  public void failsToRealizeWithUnknownOptions() {
    assertThat(realizeOnly("buffer(geom, value, {foo: 'bar'})",
        Struct.of("geom", Types.GEOMETRY, "value", Types.INTEGER)),
        failedResult(hasAncestorProblem(is(GeneralProblems.get().notAnOption(
             "foo", "options", ALLOWED_OPTIONS)))));

    assertThat(realizeOnly("buffer(geom, value, {cap: 'foo'})",
        Struct.of("geom", Types.GEOMETRY, "value", Types.INTEGER)),
        failedResult(hasAncestorProblem(is(GeneralProblems.get().notAnOption(
             "foo", "cap", Lists.newArrayList("flat", "round", "square"))))));

    assertThat(realizeOnly("buffer(geom, value, {vertex: 'foo'})",
        Struct.of("geom", Types.GEOMETRY, "value", Types.INTEGER)),
        failedResult(hasAncestorProblem(is(GeneralProblems.get().notAnOption(
             "foo", "vertex", Lists.newArrayList("bevel", "mitre", "round"))))));
  }

  @Test
  public void failsToRealizeWhenOptionsNotStatic() {
    assertThat(realizeOnly("buffer(geom, value, {join: join})",
        Struct.of("geom", Types.GEOMETRY, "value", Types.INTEGER, "join", Types.TEXT)),
        failedResult(hasAncestorProblem(is(ExpressionProblems.get().constantRequired(parse("{join: join}"))))));
  }

}
