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

import static nz.org.riskscape.engine.SRIDSet.*;

import java.io.IOException;
import java.nio.file.Path;
import java.util.Map;
import java.util.Optional;

import nz.org.riskscape.engine.FileProblems;
import org.geotools.feature.FeatureCollection;
import org.geotools.feature.FeatureIterator;
import org.geotools.geojson.feature.FeatureJSON;
import org.json.simple.parser.ParseException;
import org.geotools.api.feature.simple.SimpleFeature;
import org.geotools.api.feature.simple.SimpleFeatureType;

import com.google.common.collect.ImmutableMap;

import lombok.Getter;
import nz.org.riskscape.engine.Engine;
import nz.org.riskscape.engine.data.relation.RelationBookmarkParams;
import nz.org.riskscape.engine.data.relation.RelationBookmarkResolver;
import nz.org.riskscape.engine.projection.ForceSridProjection;
import nz.org.riskscape.engine.query.TupleUtils;
import nz.org.riskscape.engine.relation.BaseRelation;
import nz.org.riskscape.engine.relation.FeatureSourceRelation;
import nz.org.riskscape.engine.relation.FeatureSourceTupleIterator;
import nz.org.riskscape.engine.relation.Relation;
import nz.org.riskscape.engine.relation.TupleIterator;
import nz.org.riskscape.engine.types.Struct;
import nz.org.riskscape.engine.types.Struct.StructMember;
import nz.org.riskscape.problem.Problem;
import nz.org.riskscape.problem.Problems;
import nz.org.riskscape.problem.ResultOrProblems;
import nz.org.riskscape.problem.StandardCodes;

public class GeoJSONResolver extends RelationBookmarkResolver<RelationBookmarkParams> {

  public static class GeoJSONRelation extends BaseRelation {

    private final FeatureCollection featureCollection;
    @Getter
    private final String sourceInformation;

    public GeoJSONRelation(Fields fields, FeatureCollection featureCollection, String sourceInformation) {
      super(fields);
      this.featureCollection = featureCollection;
      this.sourceInformation = sourceInformation;
    }

    public GeoJSONRelation(Struct type, FeatureCollection featureCollection, String sourceInformation) {
      super(type);
      this.featureCollection = featureCollection;
      this.sourceInformation = sourceInformation;
    }

    @Override
    protected TupleIterator rawIterator() {
      @SuppressWarnings("unchecked")
      FeatureIterator<SimpleFeature> featureIterator = featureCollection.features();
      return new FeatureSourceTupleIterator(featureIterator, getRawType());
    }

    @Override
    protected BaseRelation clone(Fields fields) {
      return new GeoJSONRelation(fields, featureCollection, sourceInformation);
    }

    @Override
    public Optional<Long> size() {
      return Optional.of((long) featureCollection.size());
    }
  }

  @Getter
  private Map<String, String> extensionsToFormats = ImmutableMap.of(
      "geojson", "geojson",
      "json", "geojson"
  );

  public GeoJSONResolver(Engine engine) {
    super(engine);
  }

  @Override
  protected ResultOrProblems<Relation> createRawRelationFromBookmark(RelationBookmarkParams params) {
    FeatureJSON featureJSON = new FeatureJSON();

    ResultOrProblems<Path> geojsonFile = getBookmarkedPathOr(params);
    if (geojsonFile.hasProblems()) {
      return ResultOrProblems.failed(geojsonFile.getProblems());
    }
    try {
      SimpleFeatureType simpleType = featureJSON.readFeatureCollectionSchema(geojsonFile.get().toFile(), true);
      featureJSON.setFeatureType(simpleType);
      FeatureCollection featureCollection = featureJSON.readFeatureCollection(geojsonFile.get().toFile());

      Struct type = FeatureSourceRelation.fromFeatureType(simpleType, null, false);

      Relation relation = new GeoJSONRelation(type, featureCollection, params.bookmark.toString());
      StructMember geometryMember = TupleUtils.findGeometryMember(relation.getType(), TupleUtils.FindOption.OPTIONAL);
      if (geometryMember == null) {
        // geojson requires a geometry, but geotools doesn't seem to mind if it is missing
        return ResultOrProblems.failed(Problems.foundWith("GeoJSON",
            Problem.error(StandardCodes.GEOMETRY_REQUIRED, relation.getType())));
      }

      // GeoJSON is specified to be in CRS84. We have to use the force srid projection to assign the correct
      // SRID's to the geometries as there doens't seem to be any way to make FeatureJSON use the correct
      // geometry factory when it creates the geoms.
      return relation.project(new ForceSridProjection(EPSG4326_LONLAT, params.getProject().getSridSet()));
    } catch (IOException | IllegalStateException e) {
      // invalid json ends up in here
      Throwable cause = e.getCause();
      if (cause != null && cause instanceof ParseException) {
        return ResultOrProblems.failed(
            FileProblems.get().geotoolsCannotRead(geojsonFile.get().toFile()).withChildren(Problems.caught(cause)),
            FileProblems.get().badGeospatialDataTip(geojsonFile.get().toFile(), "GeoJSON")
        );
      }
      return ResultOrProblems.failed(Problems.caught(e));
    }
  }

}
