/*
 * 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 nz.org.riskscape.engine.Assert.*;
import static nz.org.riskscape.engine.Matchers.*;
import static org.hamcrest.CoreMatchers.hasItems;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.Matchers.contains;
import static org.junit.Assert.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.URI;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.events.XMLEvent;

import org.geotools.geometry.jts.ReferencedEnvelope;
import org.junit.Test;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.Point;

import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;

import lombok.Getter;
import nz.org.riskscape.engine.ProjectTest;
import nz.org.riskscape.engine.RiskscapeException;
import nz.org.riskscape.engine.SRIDSet;
import nz.org.riskscape.engine.Tuple;
import nz.org.riskscape.engine.gt.GeometryHelper;
import nz.org.riskscape.engine.output.FileSystemPipelineOutputStore.FileSystemPipelineContainer;
import nz.org.riskscape.engine.pipeline.sink.SaveSink;
import nz.org.riskscape.engine.relation.EmptyRelation;
import nz.org.riskscape.engine.relation.ListRelation;
import nz.org.riskscape.engine.relation.Relation;
import nz.org.riskscape.engine.resource.CreateHandle.Callback;
import nz.org.riskscape.engine.types.Nullable;
import nz.org.riskscape.engine.types.Struct;
import nz.org.riskscape.engine.types.Types;
import nz.org.riskscape.problem.Problem.Severity;
import nz.org.riskscape.problem.ResultOrProblems;


public class QGSWriterTest extends ProjectTest {

  public static class TestSink extends SaveSink {
    @Getter
    private final URI storedAt;

    public TestSink(URI uri) {
      super(mock(RiskscapeWriter.class));
      this.storedAt = uri;
    }
  }

  Map<String, SaveSink> sinks = new HashMap<>();
  Map<URI, Relation> relations = new HashMap<>();

  GeometryHelper nztmHelper = GeometryHelper.nzTransverseMercatorWithOriginShift(project.getSridSet());
  GeometryHelper latLongGeomHelper = GeometryHelper.latLong(project.getSridSet());
  GeometryHelper longLatGeomHelper = GeometryHelper.longLat(project.getSridSet());

  private void addOutput(String name, Relation relation) {
    URI uri = URI.create("file:///dummy-path/" + name);
    sinks.put(name, new TestSink(uri));
    relations.put(uri, relation);
  }

  private Relation relation(Geometry...geom) {
    Struct type = Struct.of("geom", Types.GEOMETRY);
    List<Tuple> tuples = Lists.transform(Arrays.asList(geom), g -> Tuple.ofValues(type, g));
    return new ListRelation(tuples).inferSpatialMetadata(project);
  }

  private HashSet<String> getXmlElements(InputStream is) throws Exception {
    XMLInputFactory factory = XMLInputFactory.newInstance();
    XMLEventReader reader = factory.createXMLEventReader(is);

    HashSet<String> elements = new HashSet<>();

    while (reader.hasNext()) {
      XMLEvent event = reader.nextEvent();

      if (event.isStartElement()) {
        String e = event.asStartElement().getName().getLocalPart();
        elements.add(e);
      }
    }

    reader.close();

    return elements;
  }

  private QGSWriter getWriter() {
    return new QGSWriter(sinks, uri -> ResultOrProblems.of(relations.get(uri)));
  }

  @Test
  public void boundsContainAllGeometry() throws Exception {
    addOutput("layer1", relation(longLatGeomHelper.box(1.0, 10.0, 2.0, 20.0)));
    addOutput("layer2", relation(longLatGeomHelper.box(1.5, 10.0, 2.5, 20.0)));
    addOutput("layer3", relation(longLatGeomHelper.box(1.0, 14.0, 2.0, 16.0)));

    ReferencedEnvelope bounds = getWriter().getBounds();

    assertFalse(bounds.isNull());
    assertEquals(1.0, bounds.getMinX(), 1e-5);
    assertEquals(10.0, bounds.getMinY(), 1e-5);
    assertEquals(2.5, bounds.getMaxX(), 1e-5);
    assertEquals(20.0, bounds.getMaxY(), 1e-5);
  }

  @Test
  public void boundsWillReprojectToWgs84() throws Exception {
    addOutput("foo", relation(nztmHelper.box(1.0, 10.0, 2.0, 20.0)));
    addOutput("bar", relation(nztmHelper.box(1.0, 14.0, 2.0, 16.0)));
    addOutput("baz", relation(nztmHelper.box(-1.5, 10.0, 2.5, 19.0)));

    Point expectedMin = (Point) longLatGeomHelper.reproject(nztmHelper.point(-1.5, 10.0));
    Point expectedMax = (Point) longLatGeomHelper.reproject(nztmHelper.point(2.5, 20.0));
    ReferencedEnvelope bounds = getWriter().getBounds();

    assertFalse(bounds.isNull());
    assertThat(bounds.getCoordinateReferenceSystem(), is(SRIDSet.EPSG4326_LONLAT));
    assertEquals(expectedMin.getX(), bounds.getMinX(), 1e-5);
    assertEquals(expectedMin.getY(), bounds.getMinY(), 1e-5);
    assertEquals(expectedMax.getX(), bounds.getMaxX(), 1e-5);
    assertEquals(expectedMax.getY(), bounds.getMaxY(), 1e-5);
  }

  @Test
  public void canHandleMixedOutputGeometries() throws Exception {
    addOutput("foo", relation(nztmHelper.reproject(longLatGeomHelper.point(167.5, -45.0))));
    addOutput("bar", relation(longLatGeomHelper.point(168.0, -47.0)));
    addOutput("baz", relation(latLongGeomHelper.box(-43.5, 172.0, -43.0, 171.0)));

    ReferencedEnvelope bounds = getWriter().getBounds();

    assertThat(bounds.getCoordinateReferenceSystem(), is(SRIDSet.EPSG4326_LONLAT));
    assertEquals(167.5, bounds.getMinX(), 1e-5);
    assertEquals(-47.0, bounds.getMinY(), 1e-5);
    assertEquals(172.0, bounds.getMaxX(), 1e-5);
    assertEquals(-43.0, bounds.getMaxY(), 1e-5);
  }

  @Test
  public void canHandleNoGeometryInOutputs() throws Exception {
    Relation csvRelation = new ListRelation(Tuple.ofValues(Types.INTEGER.asStruct(), 1));
    Relation nullGeom = new ListRelation(Tuple.of(Nullable.GEOMETRY.asStruct(), "value", null));
    addOutput("foo", csvRelation);
    addOutput("bar", new EmptyRelation(Types.TEXT.asStruct()));
    addOutput("baz", nullGeom);

    ReferencedEnvelope bounds = getWriter().getBounds();

    assertTrue(bounds.isNull());
    assertThat(bounds.getCoordinateReferenceSystem(), is(SRIDSet.EPSG4326_LONLAT));
  }

  @Test
  public void canHandleExceptionCreatingQGISFile() throws Exception {
    // typically an exception would be more likely to occur reading the bookmark/relation data,
    // but for simplicity it fires here when accessing the sink's URI
    SaveSink badSink = mock(SaveSink.class);
    when(badSink.getStoredAt()).thenThrow(new RiskscapeException("oopsie"));

    // setup a fake FileSystemPipelineContainer to write the QGIS project to
    FileSystemPipelineContainer container = mock(FileSystemPipelineContainer.class);
    doAnswer(inv ->  {
        Callback writeCb = (Callback) inv.getArguments()[2];
        writeCb.accept(new ByteArrayOutputStream(1024 * 10));
        return null;
    }).when(container).writeFile(any(), any(), any());
    when(container.getExecutionContext()).thenReturn(executionContext);
    when(container.getProject()).thenReturn(project);
    when(container.getSinks()).thenReturn(ImmutableMap.of("kaboom", badSink));

    // get exception when calling the constructor directly
    assertThrows(RiskscapeException.class, () -> new QGSWriter(container.getExecutionContext(), container.getSinks()));

    // but an exception writing the QGIS file shouldn't take down the whole system
    QGSWriter.write(container);
    assertThat(sunkProblems, contains(equalIgnoringChildren(
        QGSWriter.PROBLEMS.errorWritingFile().withSeverity(Severity.WARNING)
    )));
  }

  @Test
  public void outputHasExpectedXmlElements() throws Exception {
    addOutput("layer1", relation(latLongGeomHelper.point(1.0, 2.0)));
    ByteArrayOutputStream os = new ByteArrayOutputStream(1024 * 10);  // 10 KiB
    getWriter().write(os);

    ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray());
    assertThat(getXmlElements(is), hasItems("layer", "maplayer", "srs", "spatialrefsys", "wkt", "layer-tree-layer",
        "extent", "xmin", "ymin", "xmax", "ymax"));
  }
}
