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


import static nz.org.riskscape.engine.Matchers.*;
import static nz.org.riskscape.engine.SRIDSet.*;

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

import java.net.URI;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

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

import com.google.common.collect.ImmutableMap;

import nz.org.riskscape.engine.Matchers;
import nz.org.riskscape.engine.Tuple;
import nz.org.riskscape.engine.data.Bookmark;
import nz.org.riskscape.engine.data.BookmarkProblems;
import nz.org.riskscape.engine.relation.Relation;
import nz.org.riskscape.engine.resource.ResourceProblems;
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.problem.Problem.Severity;
import nz.org.riskscape.problem.ResultOrProblems;

@SuppressWarnings("unchecked")
public class KmlResolverTest extends BaseBookmarkResolverTest {

  public KmlResolverTest() {
    super("kml", engine -> new KmlResolver(engine));
  }

  @Test
  public void canReadKmlOfPoints() {
    Relation relation = from("cities.kml").get();

    Struct expectedType = Struct.of(
        "Geometry", Referenced.of(Types.GEOMETRY, crs84Helper.getCrs()),
        "name", Types.TEXT,
        "visibility", Types.BOOLEAN,
        "open", Types.BOOLEAN)
        .and("address", Types.TEXT)
        .and("phoneNumber", Types.TEXT)
        .and("description", Types.TEXT)
        .and("LookAt", Referenced.of(Types.GEOMETRY, crs84Helper.getCrs()))
        .and("Region", Referenced.of(Types.GEOMETRY, crs84Helper.getCrs()))
        .and("population", Types.INTEGER);

    assertThat(relation.getType(), is(expectedType));
    assertTrue(relation.getSpatialMetadata().isPresent());
    assertThat(relation.getSpatialMetadata().get().getCrs(), is(EPSG4326_LONLAT));
    List<Tuple> tuples = relation.iterator().collect(Collectors.toList());

    assertThat(tuples, contains(
        Tuple.ofValues(expectedType, crs84Helper.point(151, -33), "Sydney", true, true,
            null, null, "Largest city in Australia", null, null, 5300000L),
        Tuple.ofValues(expectedType, crs84Helper.point(174, -36), "Auckland", true, true,
            null, null, "Largest city in New Zealand", null, null, 1700000L),
        Tuple.ofValues(expectedType, crs84Helper.point(174, -41), "Wellington", true, true,
            null, null, "New Zealand's capital city", null, null, 436000L)
    ));

    // Let's ensure the geom has the right SRID set.
    Geometry geom = (Geometry)tuples.get(0).fetch("Geometry");
    assertEquals(project.getSridSet().get(EPSG4326_LONLAT), geom.getSRID());
  }

  @Test
  public void canRemoveEmptyFieldsWithType() {
    Relation relation = from("cities.kml",
        ImmutableMap.of("type", "struct(Geometry: geometry, name: text, description: text, population: integer)")
    ).get();

    Struct expectedType = Struct.of(
        "Geometry", Referenced.of(Types.GEOMETRY, crs84Helper.getCrs()),
        "name", Types.TEXT,
        "description", Types.TEXT,
        "population", Types.INTEGER);

    assertThat(relation.getType(), is(expectedType));
    List<Tuple> tuples = relation.iterator().collect(Collectors.toList());

    assertThat(tuples, contains(
        Tuple.ofValues(expectedType, crs84Helper.point(151, -33), "Sydney",
            "Largest city in Australia", 5300000L),
        Tuple.ofValues(expectedType, crs84Helper.point(174, -36), "Auckland",
            "Largest city in New Zealand", 1700000L),
        Tuple.ofValues(expectedType, crs84Helper.point(174, -41), "Wellington",
            "New Zealand's capital city", 436000L)
    ));
  }

  @Test
  public void errorIfNotKML() {
    // not xml at all
    ResultOrProblems<Relation> relation = from("test.geojson");
    assertThat(relation, failedResult(
        isProblem(Severity.ERROR, BookmarkProblems.class, "invalidContent")
    ));

    // xml, but not kml
    relation = from("test.xml");
    assertThat(relation, failedResult(
        is(BookmarkProblems.get().invalidContent("KML"))
    ));
  }

  @Test
  public void giveGoodErrorOnMissingRemoteFile() throws Exception {
    URI target = URI.create("https://" + HTTPS_TEST_URI + "/bogus/test.kml");
    Bookmark bookmark = new Bookmark("test", "my test bookmark", "kml",
        target,
        ImmutableMap.of("layer", Arrays.asList("test")));

    assertThat(
        resolver.resolve(bookmark, executionContext).get().getData(Relation.class),
        Matchers.failedResult(
            Matchers.hasAncestorProblem(is(ResourceProblems.get().notFound(target)))
        )
    );
  }

}
