/*
 * 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 java.util.AbstractList;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;

import org.locationtech.jts.geom.Envelope;
import org.locationtech.jts.geom.GeometryFactory;
import org.locationtech.jts.geom.LinearRing;
import org.locationtech.jts.geom.Polygon;
import org.locationtech.jts.geom.impl.PackedCoordinateSequence;

import lombok.Getter;
import lombok.RequiredArgsConstructor;
import nz.org.riskscape.engine.util.SegmentedList;

/**
 * Synthetic list of square polygon segments of `squareSize` that are formed from an internal list
 * of larger square `blocks`. These larger blocks must always be squares that are a power
 * of 2 multiple of `squareSize`, e.g. ones captured during recursively breaking up a polygon.
 *
 * This is a memory-efficient way to cut large (square) geometry by a grid. The grid-size segments only
 * need to be constructed as needed (as opposed to holding 1000s of small pieces in memory at once).
 *
 * Note that this list doesn't support random access in a performant way, but then we typically don't do random access
 * in RiskScape processing, so meh.
 */
@RequiredArgsConstructor
class BlockBasedSquareList extends AbstractList<Polygon> {

  private final GeometryFactory factory;

  /**
   * The grid size that the smaller square segments will be emitted as
   */
  private final double squareSize;
  // NB we could compress memory use further by storing a 3d array of x, y, size

  /**
   * The larger square blocks that will be broken down into smaller square segments
   */
  @Getter
  private final List<Envelope> blocks = SegmentedList.forClass(Envelope.class);

  /**
   * the total number of smaller square segments that comprise the larger square blocks
   */
  private int totalSegments = 0;

  /**
   * Add a new block of squares to the list. The given envelope will be divided up
   * into smaller square segments, based on the `squareSize`.
   */
  void addBlock(Envelope envelope) {
    // sanity-check future developers don't pass in the wrong size blocks
    assert isBlockSizeRoughlyValid(envelope);

    blocks.add(envelope);
    totalSegments += segmentsPerSide(envelope) * segmentsPerSide(envelope);
  }

  @Override
  public Polygon get(int index) {
    int idx = 0;
    Iterator<Polygon> iter = iterator();
    while (index > idx++) {
      iter.next();
    }

    return iter.next();
  }

  @Override
  public Iterator<Polygon> iterator() {
    Iterator<Envelope> envIter = blocks.iterator();

    return new Iterator<Polygon>() {

      int curSize = 0;
      int pos = 0;
      Envelope curEnv;
      int segmentsInCurEnv = 0;

      @Override
      public boolean hasNext() {
        // I can't imagine we'll ever get given empty envelopes, but if we do, this would need to be a while loop
        if (segmentsInCurEnv == pos) {
          // we've reached the end of the current envelope, move onto the next one
          if (envIter.hasNext()) {
            curEnv = envIter.next();
            pos = 0;
            curSize = segmentsPerSide(curEnv);
            segmentsInCurEnv = curSize * curSize;
          } else {
            return false;
          }
        }

        return true;
      }

      @Override
      public Polygon next() {
        if (segmentsInCurEnv == pos) {
          if (!hasNext()) {
            throw new NoSuchElementException();
          }
        }

        // we start at the bottom left of the envelope and iterate through the blocks
        // moving from left to right
        double originx = curEnv.getMinX();
        double originy = curEnv.getMinY();

        int xpos = pos % curSize;
        int ypos = pos == 0 ? 0 : (pos - xpos) / curSize;
        double minx = originx + (xpos * squareSize);
        double miny = originy + (ypos * squareSize);
        double maxx = minx + squareSize;
        double maxy = miny + squareSize;

        LinearRing ring = new LinearRing(new PackedCoordinateSequence.Double(new double[] {
          minx, miny,
          minx, maxy,
          maxx, maxy,
          maxx, miny,
          minx, miny
        }, 2, 0), factory);

        pos++;

        return new Polygon(ring, null, factory);
      }
    };
  }

  @Override
  public int size() {
    return totalSegments;
  }

  /**
   * @return the number of smaller square segments that fit along one side of the larger envelope block
   */
  private int segmentsPerSide(Envelope envelope) {
    return (int) Math.round(envelope.getWidth() / squareSize);
  }

  private boolean isBlockSizeRoughlyValid(Envelope envelope) {
    // We will produce incorrect results if given anything that's not a square/multiple of squareSize.
    // We can't be too precise here due to floating point math, but given we should be in metric map units,
    // being out by > 1m should indicate we were given bad input
    boolean isSquare = Math.abs(envelope.getWidth() - envelope.getHeight()) < 1;
    double expectedSize = squareSize * segmentsPerSide(envelope);
    boolean isExpectedSize = Math.abs(envelope.getWidth() - expectedSize) < 1;
    return isSquare && isExpectedSize;
  }
}
