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

import static nz.org.riskscape.engine.Assert.*;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;

import java.util.ArrayList;
import java.util.List;

import org.junit.Test;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.Envelope;
import org.locationtech.jts.geom.GeometryFactory;
import org.locationtech.jts.geom.LinearRing;
import org.locationtech.jts.geom.Point;
import org.locationtech.jts.geom.Polygon;
import org.locationtech.jts.geom.impl.PackedCoordinateSequence;

import nz.org.riskscape.engine.GeometryMatchers;

public class BlockBasedSquareListTest {

  GeometryFactory factory = new GeometryFactory();

  @Test
  public void canTurnSquaresIntoAListOfBlocks() {
    // divide a 10x10 envelope into 1x1 squares
    Envelope env = envelope(0, 0, 10, 10);
    BlockBasedSquareList subject = new BlockBasedSquareList(factory, 1.0);

    subject.addBlock(env);
    assertEquals(100, subject.size());

    assertThat(subject.get(0), GeometryMatchers.geometryTopoMatch(square(0, 0, 1, 1)));

    assertThat(subject.get(99), GeometryMatchers.geometryTopoMatch(square(9, 9, 10, 10)));

    // add an extra 1x1 non-contiguous envelope
    env = envelope(20, 20, 21, 21);
    subject.addBlock(env);
    assertThat(subject.get(100), GeometryMatchers.geometryTopoMatch(square(20, 20, 21, 21)));
    assertEquals(101, subject.size());

    // sanity-check the Polygons coming out are the same factory as going in
    assertEquals(subject.get(0).getFactory(), factory);
  }

  @Test
  public void canIterateBlocksCorrectly() {
    // align a 10x10 block so the centroids are whole numbers 1-10
    Envelope env = envelope(0.5, 0.5, 10.5, 10.5);
    BlockBasedSquareList subject = new BlockBasedSquareList(factory, 1.0);
    subject.addBlock(env);
    // add a second 5x5 block in the negative space, just for kicks
    env = envelope(-50.5, -100.5, -55.5, -105.5);
    subject.addBlock(env);

    // just check we get the centroid back for each expected square (don't care what order)
    List<Point> centroids = new ArrayList<>();
    subject.forEach(sq -> centroids.add(sq.getCentroid()));
    assertThat(centroids.size(), is(125));

    for (int x = 1; x <= 10; x++) {
      for (int y = 1; y <= 10; y++) {
        assertThat(centroids, hasItem(GeometryMatchers.geometryTopoMatch(point(x, y))));
      }
    }

    for (int x = -51; x >= -55; x--) {
      for (int y = -101; y >= -105; y--) {
        assertThat(centroids, hasItem(GeometryMatchers.geometryTopoMatch(point(x, y))));
      }
    }
  }

  @Test
  public void canRejectBlatantlyBadEnvelopes() {
    // cannot divide a 10x10 envelope into 3x3 squares
    BlockBasedSquareList subject = new BlockBasedSquareList(factory, 3.0);
    assertThrows(AssertionError.class, () -> subject.addBlock(envelope(0, 0, 10, 10)));

    // small floating point math differences should still be OK
    Envelope env = envelope(0.00001, 0.00001, 8.99997, 8.99997);
    subject.addBlock(env);
    assertEquals(9, subject.size());

    // cannot add non-square blocks
    assertThrows(AssertionError.class, () -> subject.addBlock(envelope(0, 0, 9, 12)));
    assertThrows(AssertionError.class, () -> subject.addBlock(envelope(0, 0, 12, 9)));

    // small floating point math differences should still be OK
    env = envelope(0, 0, 8.99997, 9.00001);
    subject.addBlock(env);
    env = envelope(0, 0, 9.00001, 8.99997);
    subject.addBlock(env);
    env = envelope(-0.0001, 0.00003, 9.00001, 8.99997);
    subject.addBlock(env);
  }

  private Polygon square(double minx, double miny, double maxx, double maxy) {
    return new Polygon(new LinearRing(new PackedCoordinateSequence.Double(new double[] {
        minx, miny,
        minx, maxy,
        maxx, maxy,
        maxx, miny,
        minx, miny
    }, 2, 0), factory), null, factory);
  }

  private Point point(double x, double y) {
    return factory.createPoint(new Coordinate(x, y));
  }

  private Envelope envelope(double minx, double miny, double maxx, double maxy) {
    return square(minx, miny, maxx, maxy).getEnvelopeInternal();
  }
}
