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

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

import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.CoordinateSequence;
import org.locationtech.jts.geom.GeometryFactory;
import org.locationtech.jts.geom.LineSegment;
import org.locationtech.jts.geom.LineString;
import org.locationtech.jts.geom.MultiLineString;

import com.google.common.collect.Lists;

import lombok.RequiredArgsConstructor;

@RequiredArgsConstructor
public class SegmentLineStringOp {

  public List<LineString> apply(MultiLineString toSegment, double distance) {
    int numLineStrings = toSegment.getNumGeometries();
    List<List<LineString>> allGeometries = new ArrayList<>(numLineStrings);
    int requiredSize = 0;
    for (int i = 0; i < numLineStrings; i++) {
      LineString lineString = (LineString) toSegment.getGeometryN(i);
      List<LineString> forThisLineString = apply(lineString, distance);
      allGeometries.add(forThisLineString);
      requiredSize += forThisLineString.size();
    }

    List<LineString> finalList = new ArrayList<>(requiredSize);
    for (List<LineString> perLineString : allGeometries) {
      finalList.addAll(perLineString);
    }

    return finalList;
  }


  public List<LineString> apply(LineString geometry, double distance) {

    //  - measure distance from the previous segmented geometry's last coordinate
    //
    //    - if it's > distance
    //      - find coordinate along line where measured_length = distance
    //      - this coordinate is the end of the line, and the start of a new one
    //      - add new linestring to the list, next coordinate


    CoordinateSequence originalPoints = geometry.getCoordinateSequence();

    // empty linestring, return the given geometry to avoid segmenting operations from skipping exposures that have
    // empty an geometry (#1603)
    if (originalPoints.size() == 0) {
      return List.of(geometry);
    }


    LinkedList<LineString> built = new LinkedList<>();
    LinkedList<Coordinate> collected = new LinkedList<>();
    Coordinate lastCut = originalPoints.getCoordinate(0);
    Coordinate lastCoord = lastCut;
    double distanceSoFar = 0;

    // for each coordinate...
    int idx = 0;
    while (idx < originalPoints.size()) {
      Coordinate curCoord = originalPoints.getCoordinate(idx);
      double distanceBetween = lastCoord.distance(curCoord);
      distanceSoFar += distanceBetween;

      // we need to find out where segmentDistance is between the previous coordinate and cur
      if (distanceSoFar >= distance) {
        double cutDistance = distance - (distanceSoFar - distanceBetween);
        Coordinate cutPoint = findCutPoint(lastCoord, curCoord, cutDistance);
        collected.add(cutPoint);
        built.add(build(geometry.getFactory(), collected));
        lastCoord = cutPoint;

        // reset for next segment
        collected.clear();
        distanceSoFar = 0;

        boolean addCutPoint;
        if (cutPoint.equals(curCoord)) {
          // amazingly, we cut the line exactly on its end - no need to revisit curCoord again
          // But, if we cut the line between start and end, then we need to visit curCoord once more (so we don't
          // increment idx) to work out if it's still too far out from the last cut to be in its own segment or not
          idx++;

          // don't add the final point in to the collected list - it'll die when we try to create a line string from it
          addCutPoint = idx < originalPoints.size();
        } else {
          addCutPoint = true;
        }

        if (addCutPoint) {
          collected.add(cutPoint);
        }
        lastCut = cutPoint;
      } else {
        collected.add(curCoord);
        lastCoord = curCoord;
        idx++;
      }
    }

    // add the trailing segment to the list
    if (!collected.isEmpty()) {
      built.add(build(geometry.getFactory(), collected));
    }

    // convert it to an array list - we take the cost of the conversion to avoid the memory penalty and slower access
    // in the future
    return Lists.newArrayList(built);
  }

  private Coordinate findCutPoint(Coordinate from, Coordinate to, double distance) {
    if (distance == 0) {
      return from;
    }

    LineSegment segment = new LineSegment(from, to);
    double length = segment.getLength();

    if (distance == length) {
      return to;
    }

    if (length == 0) {
      return from;
    }

    double fraction = distance / length;
    return segment.pointAlong(fraction);
  }

  private LineString build(GeometryFactory factory, LinkedList<Coordinate> collected) {
    return factory.createLineString(collected.toArray(new Coordinate[collected.size()]));
  }

}
