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

import java.io.IOException;
import java.util.List;

import org.geotools.api.data.FeatureSource;
import org.geotools.api.data.Query;
import org.geotools.data.simple.SimpleFeatureIterator;
import org.geotools.api.data.SimpleFeatureSource;
import org.geotools.feature.FeatureIterator;
import org.locationtech.jts.geom.Geometry;
import org.geotools.api.feature.simple.SimpleFeature;
import org.geotools.api.referencing.crs.CoordinateReferenceSystem;

import lombok.Getter;
import lombok.NonNull;
import nz.org.riskscape.engine.RiskscapeIOException;
import nz.org.riskscape.engine.SRIDSet;
import nz.org.riskscape.engine.Tuple;
import nz.org.riskscape.engine.data.InputDataProblems;
import nz.org.riskscape.engine.data.relation.FeatureSourceBookmarkResolver;
import nz.org.riskscape.engine.types.Struct;
import nz.org.riskscape.engine.types.Struct.StructMember;
import nz.org.riskscape.problem.Problem;

/**
 * A {@link TupleIterator} backed by a {@link FeatureIterator}.  Converts {@link SimpleFeature}s to {@link Tuple}s
 * on the fly according to the given type.
 */
public class FeatureSourceTupleIterator implements nz.org.riskscape.engine.relation.TupleIterator {

  public final FeatureIterator<SimpleFeature> internal;

  /**
   * Creates a new {@link FeatureSourceTupleIterator}
   * @param featureSource a {@link FeatureSource} to pull features from
   * @param query a query to use when building the {@link SimpleFeatureIterator}.
   * @param sridSet the sridset to use for mapping {@link CoordinateReferenceSystem}s to SRID
   * ({@link Geometry#getSRID()})
   * @param type the struct that {@link Tuple}s will use.
   * @return a new {@link FeatureSourceTupleIterator}
   */
  public static FeatureSourceTupleIterator fromQuery(
      @NonNull SimpleFeatureSource featureSource,
      @NonNull Query query,
      @NonNull SRIDSet sridSet,
      @NonNull Struct type,
      @NonNull CoordinateReferenceSystem crs) {

    SimpleFeatureIterator features;
    try {
      org.geotools.api.data.Query hintedQuery =
          sridSet.queryWithHints(Query.ALL, crs);

      query.setHints(hintedQuery.getHints());
      features = featureSource.getFeatures(query).features();
    } catch (IOException e) {

      throw new RiskscapeIOException(String.format("Error while requesting features from feature source %s",
          featureSource), e);
    }

    return new FeatureSourceTupleIterator(features, type);
  }

  public FeatureSourceTupleIterator(FeatureIterator<SimpleFeature> iterator, Struct type) {
    this.internal = iterator;
    this.type = type;
  }

  @Getter
  public final Struct type;
  private boolean finished = false;

  @Override
  public boolean hasNext() {
    if (finished) {
      return false;
    }

    finished = !internal.hasNext();

    return !finished;
  }

  @Override
  public Tuple next() {
    SimpleFeature sf = internal.next();
    Tuple tuple = new Tuple(type);
    Problem tupleProblem = null;

    List<StructMember> members = getType().getMembers();
    for (StructMember member : members) {

      if (member.getType() == FeatureSourceRelation.FID_TYPE) {
        tuple.set(member, sf.getID());
      } else {
        Object value = sf.getAttribute(member.getKey());
        if (value != null) {
          tuple.set(member, member.getType().coerce(value));
        } else {
          // check the geometry member never has a null value (Null geometry is valid in
          // shapefiles, but riskscape models won't do anything sensible with these tuples)
          StructMember geomMember = FeatureSourceRelation.geometryStructMember(type, sf.getFeatureType());
          if (member.equals(geomMember)) {
            tupleProblem = InputDataProblems.get().nullGeometry(geomMember.getKey(), sf.getID());
          }
        }
      }
    }
    if (tupleProblem != null) {
      throw new InvalidTupleException(tuple, tupleProblem);
    }

    return tuple;
  }

  @Override
  protected void finalize() throws Throwable {
    close();
  }

  @Override
  public void close() {
    FeatureSourceBookmarkResolver.LOCK_DEFEATER.call("close", () -> {
      this.internal.close();
      return null;
    });
  }
}
