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

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

import java.io.File;
import java.util.Arrays;

import org.geotools.referencing.CRS;
import org.junit.Test;

import nz.org.riskscape.engine.CrsHelper;
import nz.org.riskscape.engine.ProjectTest;
import nz.org.riskscape.engine.coverage.TypedCoverage;
import nz.org.riskscape.engine.data.Bookmark;
import nz.org.riskscape.engine.data.ResolvedBookmark;
import nz.org.riskscape.problem.Problem;

public class CoverageFileResolverTest extends ProjectTest implements CrsHelper {

  CoverageFileBookmarkResolver resolver = new CoverageFileBookmarkResolver(engine);
  Bookmark plain = Bookmark.builder().location(getPackagePath().resolve("plain.asc").toUri()).build();
  Bookmark withPrj = Bookmark.builder().location(getPackagePath().resolve("with-wkt-prj.asc").toUri()).build();
  Bookmark withBadPrj = Bookmark.builder().location(getPackagePath().resolve("with-bad-prj.asc").toUri()).build();
  Bookmark geotiff = Bookmark.builder().location(getPackagePath().resolve("grid-tiff.tif").toUri()).build();
  GridTypedCoverage coverage;

  @Test
  public void canResolveAnAsciiGrid() {
    resolve(plain);
    assertEquals(TypedCoverage.DEFAULT_CRS, coverage.getCoordinateReferenceSystem());
  }

  @Test
  public void canResolveAnAsciiGridWithMapValue() {
    plain.getUnparsed().put("map-value", Arrays.asList("value"));
    ResolvedBookmark resolved = resolver.resolve(plain, executionContext).get();
    assertThat(resolved.getDataType(), is(MappedCoverage.class));
    MappedCoverage mappedCoverage = resolved.getData(MappedCoverage.class).get();
    assertEquals(TypedCoverage.DEFAULT_CRS, mappedCoverage.getCoordinateReferenceSystem());
  }

  @Test
  public void canResolveAnAsciiGridWithCrsOverridden() throws Exception {
    plain.getUnparsed().put("crs-name", Arrays.asList("EPSG:2193"));
    resolve(plain);
    assertNotEquals(TypedCoverage.DEFAULT_CRS, coverage.getCoordinateReferenceSystem());
    assertEquals(CRS.decode("EPSG:2193", true), coverage.getCoordinateReferenceSystem());
  }

  @Test
  public void canResolveAnAsciiGridWithAWktFormattedPrjFile() throws Exception {
    resolve(withPrj);
    assertNotEquals(TypedCoverage.DEFAULT_CRS, coverage.getCoordinateReferenceSystem());
    assertTrue(CRS.equalsIgnoreMetadata(CRS.decode("EPSG:2193"), coverage.getCoordinateReferenceSystem()));
  }

  @Test
  public void canResolveAnAsciiGridWithAWktFormattedPrjFileWithCrsOverridden() throws Exception {
    withPrj.getUnparsed().put("crs-name", Arrays.asList("EPSG:27200"));
    resolve(withPrj);
    assertFalse(CRS.equalsIgnoreMetadata(CRS.decode("EPSG:2193"), coverage.getCoordinateReferenceSystem()));
    assertTrue(CRS.equalsIgnoreMetadata(CRS.decode("EPSG:27200", true), coverage.getCoordinateReferenceSystem()));
  }

  @Test
  public void canResolveAnAsciiGridWithForceXYOff() throws Exception {
    plain.getUnparsed().put("crs-name", Arrays.asList("EPSG:4326"));
    plain.getUnparsed().put("crs-longitude-first", Arrays.asList("false")); // aka crs-force-xy
    resolve(plain);
    assertTrue(CRS.equalsIgnoreMetadata(CRS.decode("EPSG:4326", false), coverage.getCoordinateReferenceSystem()));
  }

  @Test
  public void canGetNiceErrorIfPrjUnsupported() throws Exception {
    ResolvedBookmark resolved = resolver.resolve(withBadPrj, executionContext).get();

    Problem problem = resolved.getData(GridTypedCoverage.class).getProblems().get(0);
    assertThat(render(problem), containsString("with-bad-prj.prj is in an unsupported format"));
    assertThat(problem.getAffected(File.class).get().getName(), is("with-bad-prj.prj"));
  }

  @Test
  public void canReadUnsupportedPrjWithCrsOverride() throws Exception {
    withBadPrj.getUnparsed().put("crs-name", Arrays.asList("EPSG:2193"));
    resolve(withBadPrj);
    assertEquals(CRS.decode("EPSG:2193", true), coverage.getCoordinateReferenceSystem());
  }

  @Test
  public void canReadGeoTiffWithCrsOverride() throws Exception {
    // read geotiff as is, with no CRS override. Note GeoTIFFs are in X,Y order
    resolve(geotiff);
    assertEquals(CRS.decode("EPSG:4326", true), coverage.getCoordinateReferenceSystem());

    // override CRS to same setting. This can be useful to suppress datum shift warnings
    geotiff.getUnparsed().put("crs-name", Arrays.asList("EPSG:4326"));
    resolve(geotiff);
    assertEquals(CRS.decode("EPSG:4326", true), coverage.getCoordinateReferenceSystem());

    // override CRS to a different setting (Kinda dumb, but we let the user do dumb stuff)
    geotiff.getUnparsed().put("crs-name", Arrays.asList("EPSG:2193"));
    resolve(geotiff);
    assertEquals(CRS.decode("EPSG:2193", true), coverage.getCoordinateReferenceSystem());

    // override X,Y order. Highly unlikely, but just in case there are GeoTIFFs out
    // there that don't conform to the standard, and is consistent with shapefiles
    geotiff.getUnparsed().put("crs-name", Arrays.asList("EPSG:2193"));
    geotiff.getUnparsed().put("crs-longitude-first", Arrays.asList("false"));
    resolve(geotiff);
    assertEquals(CRS.decode("EPSG:2193", false), coverage.getCoordinateReferenceSystem());
  }

  private void resolve(Bookmark bookmark) {
    ResolvedBookmark resolved = resolver.resolve(bookmark, executionContext).get();
    coverage = resolved.getData(GridTypedCoverage.class).get();

  }

}
