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

import static org.junit.Assert.*;

import java.util.Arrays;
import java.util.stream.Collectors;

import org.junit.Test;
import org.skyscreamer.jsonassert.JSONAssert;

import nz.org.riskscape.engine.ProjectTest;
import nz.org.riskscape.engine.Tuple;
import nz.org.riskscape.engine.gt.GeometryHelper;
import nz.org.riskscape.engine.resource.ByteArrayCreateHandle;
import nz.org.riskscape.engine.types.Nullable;
import nz.org.riskscape.engine.types.RSList;
import nz.org.riskscape.engine.types.Struct;
import nz.org.riskscape.engine.types.Types;

public class GeoJSONWriterTest extends ProjectTest {

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

  @Test
  public void noFeaturesWritesValidGeoJson() throws Exception {
    Struct type = Struct.of("geom", Types.GEOMETRY, "value", Types.TEXT);

    String written = write(type);

    JSONAssert.assertEquals(
        """
        {
          "type":"FeatureCollection",
          "features":[
          ]
        }
        """, written, true);

  }

  @Test
  public void canWriteUnnestedTuples() throws Exception {
    Struct type = Struct.of("geom", Types.GEOMETRY, "value", Types.TEXT);

    String written = write(type,
        Tuple.ofValues(type, latLongHelper.point(10, 15), "foo"),
        Tuple.ofValues(type, latLongHelper.point(20, 25), "bar")
    );

    // Note that our json coordinates are long/lat rather than the lat/long used in the properties
    String expected = expectedOf(
        "{\"type\":\"Feature\",\"geometry\":{\"coordinates\":[15,10],\"type\":\"Point\"},"
        + "\"properties\":{\"value\":\"foo\"}}",
        "{\"type\":\"Feature\",\"geometry\":{\"coordinates\":[25,20],\"type\":\"Point\"},"
        + "\"properties\":{\"value\":\"bar\"}}");
    JSONAssert.assertEquals(expected, written, true);
  }

  @Test
  public void doesNotDuplicateGeometryEntries() throws Exception {
    Struct type = Struct.of("geometry", Types.GEOMETRY, "value", Types.TEXT);

    String written = write(type,
        Tuple.ofValues(type, latLongHelper.point(10, 15), "foo"),
        Tuple.ofValues(type, latLongHelper.point(20, 25), "bar")
    );

    // Note that our json coordinates are long/lat rather than the lat/long used in the properties
    String expected = expectedOf(
        "{\"type\":\"Feature\",\"geometry\":{\"coordinates\":[15,10],\"type\":\"Point\"},"
        + "\"properties\":{\"value\":\"foo\"}}",
        "{\"type\":\"Feature\",\"geometry\":{\"coordinates\":[25,20],\"type\":\"Point\"},"
        + "\"properties\":{\"value\":\"bar\"}}");
    JSONAssert.assertEquals(expected, written, true);
  }

  @Test
  public void canWriteNullGeometries() throws Exception {
    Struct type = Struct.of("geom", Nullable.GEOMETRY, "value", Types.TEXT);

    String written = write(type,
        Tuple.ofValues(type, null, "foo"),
        Tuple.ofValues(type, latLongHelper.point(20, 25), "bar")
    );

    // Note that our json coordinates are long/lat rather than the lat/long used in the properties
    String expected = expectedOf(
        "{\"type\":\"Feature\","
        + "\"properties\":{\"value\":\"foo\"}}",
        "{\"type\":\"Feature\",\"geometry\":{\"coordinates\":[25,20],\"type\":\"Point\"},"
        + "\"properties\":{\"value\":\"bar\"}}");
    JSONAssert.assertEquals(expected, written, true);
  }

  @Test
  public void canWriteMultiPoint() throws Exception {
    Struct type = Struct.of("geom", Types.GEOMETRY, "value", Types.TEXT);

    String written = write(type, Tuple.ofValues(type,
        latLongHelper.multiPoint(latLongHelper.point(10, 15), latLongHelper.point(30, 15)),
        "foo"));
    // Note that our json coordinates are long/lat rather than the lat/long used in the properties
    String expected = expectedOf(
        "{\"type\":\"Feature\",\"geometry\":{\"coordinates\":[[15,10],[15,30]],\"type\":\"MultiPoint\"},"
            + "\"properties\":{\"value\":\"foo\"}}");
    JSONAssert.assertEquals(expected, written, true);
  }

  @Test
  public void canWriteLines() throws Exception {
    Struct type = Struct.of("geom", Types.GEOMETRY, "value", Types.TEXT);

    String written = write(type, Tuple.ofValues(type, latLongHelper.line(10, 15, 20, 15), "foo"));

    // Note that our json coordinates are long/lat rather than the lat/long used in the properties
    String expected = expectedOf(
        "{\"type\":\"Feature\",\"geometry\":{\"coordinates\":[[15,10],[15,20]],\"type\":\"LineString\"},"
            + "\"properties\":{\"value\":\"foo\"}}");
    JSONAssert.assertEquals(expected, written, true);
  }

  @Test
  public void canWriteMultiLines() throws Exception {
    Struct type = Struct.of("geom", Types.GEOMETRY, "value", Types.TEXT);

    String written = write(type, Tuple.ofValues(type,
        latLongHelper.multiLine(latLongHelper.line(10, 15, 20, 15), latLongHelper.line(30, 15, 40, 15)),
        "foo"));

    // Note that our json coordinates are long/lat rather than the lat/long used in the properties
    String expected = expectedOf(
        "{\"type\":\"Feature\",\"geometry\":{\"coordinates\":[[[15,10],[15,20]],[[15,30],[15,40]]],"
            + "\"type\":\"MultiLineString\"},"
            + "\"properties\":{\"value\":\"foo\"}}");
    JSONAssert.assertEquals(expected, written, true);
  }

  @Test
  public void canWritePolygons() throws Exception {
    Struct type = Struct.of("geom", Types.GEOMETRY, "value", Types.TEXT);

    String written = write(type, Tuple.ofValues(type, latLongHelper.box(10, 10, 20, 20), "foo"));
    // Note that our json coordinates are long/lat rather than the lat/long used in the properties
    String expected = expectedOf(
        "{\"type\":\"Feature\",\"geometry\":{\"coordinates\":[[[10,10],[10,20],[20,20],[20,10],[10,10]]],"
            + "\"type\":\"Polygon\"},"
            + "\"properties\":{\"value\":\"foo\"}}");
    JSONAssert.assertEquals(expected, written, true);
  }

  @Test
  public void canWriteMultiPolygons() throws Exception {
    Struct type = Struct.of("geom", Types.GEOMETRY, "value", Types.TEXT);

    String written = write(type, Tuple.ofValues(type,
        latLongHelper.multiBox(latLongHelper.box(10, 10, 20, 20), latLongHelper.box(30, 10, 40, 20)),
        "foo"));
    // Note that our json coordinates are long/lat rather than the lat/long used in the properties
    String expected = expectedOf(
        "{\"type\":\"Feature\",\"geometry\":{\"coordinates\":"
            + "[[[[10,10],[10,20],[20,20],[20,10],[10,10]]],[[[10,30],[10,40],[20,40],[20,30],[10,30]]]],"
            + "\"type\":\"MultiPolygon\"},\"properties\":{\"value\":\"foo\"}}");

    JSONAssert.assertEquals(expected, written, true);
  }

  @Test
  public void canWriteNumberTypes() throws Exception {
    Struct type = Struct.of("geom", Types.GEOMETRY, "value", Types.TEXT,
        "int", Types.INTEGER, "float", Types.FLOATING);

    String written = write(type, Tuple.ofValues(type, latLongHelper.point(10, 15), "foo", 10L, 15D));

    // Note that our json coordinates are long/lat rather than the lat/long used in the properties
    String expected = expectedOf(
        "{\"type\":\"Feature\",\"geometry\":{\"coordinates\":[15,10],\"type\":\"Point\"},"
        + "\"properties\":{\"value\":\"foo\", \"int\": 10, \"float\": 15.0}}");
    JSONAssert.assertEquals(expected, written, true);
  }

  @Test
  public void canWriteWithNullableTypes() throws Exception {
    Struct type = Struct.of("geom", Types.GEOMETRY, "value", Types.TEXT,
        "int", Nullable.INTEGER, "float", Nullable.FLOATING);

    String written = write(type,
        Tuple.ofValues(type, latLongHelper.point(10, 15), "foo", null, 15D)
    );

    // Note that our json coordinates are long/lat rather than the lat/long used in the properties
    String expected = expectedOf(
        "{\"type\":\"Feature\",\"geometry\":{\"coordinates\":[15,10],\"type\":\"Point\"},"
        + "\"properties\":{\"value\":\"foo\", \"int\": null, \"float\": 15.0}}");
    JSONAssert.assertEquals(expected, written, true);
  }

  @Test
  public void canWriteListType() throws Exception {
    Struct type = Struct.of("geom", Types.GEOMETRY, "value", RSList.create(Types.TEXT));

    String written = write(type,
        Tuple.ofValues(type, latLongHelper.point(10, 15), Arrays.asList("foo", "bar"))
    );

    // Note that our json coordinates are long/lat rather than the lat/long used in the properties
    String expected = expectedOf(
        "{\"type\":\"Feature\",\"geometry\":{\"coordinates\":[15,10],\"type\":\"Point\"},"
        + "\"properties\":{\"value\":[\"foo\", \"bar\"]}}");
    JSONAssert.assertEquals(expected, written, true);
  }

  @Test
  public void canWriteNestedTuple() throws Exception {
    Struct child = Struct.of("geom", Types.GEOMETRY, "value", Types.TEXT);
    Struct type = Struct.of("c1", child, "c2", child);

    String written = write(type, Tuple.ofValues(type,
        Tuple.ofValues(child, latLongHelper.point(10, 15), "foo"),
        Tuple.ofValues(child, latLongHelper.point(20, 25), "bar")
    ));

    // Note that our json coordinates are long/lat rather than the lat/long used in the properties
    String expected = expectedOf(
        "{\"type\":\"Feature\",\"geometry\":{\"coordinates\":[15,10],\"type\":\"Point\"},"
        + "\"properties\":{\"c1.value\":\"foo\","
        + "\"c2.geom\":\"POINT (20 25)\",\"c2.value\":\"bar\"}}");
    JSONAssert.assertEquals(expected, written, true);
  }

  @Test
  public void memberNamedGeometryCanBeRenamed() throws Exception {
    // bit of a corner case here. If the struct has a member called geometry that isn't the features geometry
    // member then it needs to be renamed to avoid a name clash should RiskScape read the file back in.
    // in this case geometry -> geometry-2 as we can't used geometry-1 as that already exists to.
    Struct type = Struct.of("the_geom", Types.GEOMETRY, "geometry", Types.TEXT, "geometry-1", Types.TEXT);

    String written = write(type, Tuple.ofValues(type, latLongHelper.point(10, 15), "foo", "bar"));

    String expected = expectedOf(
        "{\"type\":\"Feature\",\"geometry\":{\"coordinates\":[15,10],\"type\":\"Point\"},"
        + "\"properties\":{\"geometry-2\":\"foo\",\"geometry-1\":\"bar\"}}");
    JSONAssert.assertEquals(expected, written, true);
  }

  private String expectedOf(String... items) {
    StringBuilder sb = new StringBuilder("{\"type\":\"FeatureCollection\", \"features\":[");

    sb.append(Arrays.stream(items).collect(Collectors.joining(",")));
    sb.append("]}");
    return sb.toString();
  }

  private String write(Struct type, Tuple... values) throws Exception {
    ByteArrayCreateHandle handle = new ByteArrayCreateHandle();
    RiskscapeWriter writer = GeoJSONWriter.of(type, handle, project).get();
    for (Tuple value : values) {
      writer.write(value);
    }
    writer.close();
    return handle.getWritten();
  }

}
