/*
 * 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 nz.org.riskscape.engine.TupleMatchers.*;

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

import java.net.URI;
import java.nio.file.Paths;

import org.geotools.coverage.grid.GridCoverage2D;
import org.hamcrest.Matcher;
import org.junit.Before;
import org.junit.Test;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.GeometryFactory;
import org.locationtech.jts.geom.Polygon;

import nz.org.riskscape.engine.ProjectTest;
import nz.org.riskscape.engine.RelationMatchers;
import nz.org.riskscape.engine.SRIDSet;
import nz.org.riskscape.engine.Tuple;
import nz.org.riskscape.engine.coverage.TypedCoverage;
import nz.org.riskscape.engine.data.Bookmark;

public class GridCoverageRelationTest extends ProjectTest {


  GeometryFactory gf;

  @Before
  public void setup() {
    gf = project.getSridSet().getGeometryFactory(SRIDSet.EPSG2193_NZTM);
  }

  @Test
  public void iteratesThroughAllThePixelsYieldingPointsInTheCentreForEach() {
    URI uri = Paths.get(
        "src", "test", "resources", "nz", "org", "riskscape", "engine", "data", "coverage", "plain.asc").toUri();

    engine.getBookmarkResolvers().add(new CoverageFileBookmarkResolver(engine));

    GridTypedCoverage typedCoverage = (GridTypedCoverage) engine.getBookmarkResolvers()
        .resolveAndValidate(Bookmark.fromURI(uri), executionContext, TypedCoverage.class)
        .get().getData(TypedCoverage.class).get();

    GridCoverage2D coverage = (GridCoverage2D) typedCoverage.getCoverage();
    new GridTypedCoverage(coverage, project.getSridSet());
    GridCoverageRelation relation = GridCoverageRelation.create(typedCoverage, coverage);

    // all values that are within bounds and not nodata are represented here
    assertThat(
      relation,
      RelationMatchers.relationWithTuples(containsInAnyOrder(
        matchesValue(1, 1, 0),
        matchesValue(1, 2, 1),  matchesValue(1, 3, 1), matchesValue(1, 4, 1),
        matchesValue(2, 2, 2),  matchesValue(2, 3, 2), matchesValue(2, 4, 2),
        matchesValue(3, 2, 3),  matchesValue(3, 3, 3), matchesValue(3, 4, 3)
      ))
    );
  }

  Matcher<Tuple> matchesValue(int value, int px, int py) {
    // .asc pixel -> geometry working shown in laborious detail
    final int xllcorner = 1580000;
    final int yllcorner = 5475000;
    final int cellsize = 100;
    final int numrows = 4;
    // y goes bottom to top
    final int ystarts = yllcorner + cellsize * numrows;
    // x goes left to right
    final int xstarts = xllcorner;

    // x goes left to right
    double x = xstarts + (px * cellsize);
    // y goes bottom to top
    double y = ystarts - (py * cellsize);

    return allOf(
      tupleWithValue("value", equalTo((double) value)),
      tupleWithValue("geom", equalTo(nztmPolygon(x, y, cellsize)))
    );
  }

  Polygon nztmPolygon(double x, double y, int cellsize) {
    return gf.createPolygon(new Coordinate[] {
      new Coordinate(x, y - cellsize),
      new Coordinate(x + cellsize, y - cellsize),
      new Coordinate(x + cellsize, y),
      new Coordinate(x, y),
      new Coordinate(x, y - cellsize),
    });
  }

}
