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

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;

import org.geotools.api.referencing.crs.CoordinateReferenceSystem;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.GeometryFactory;

import lombok.Getter;
import lombok.RequiredArgsConstructor;
import nz.org.riskscape.engine.RiskscapeException;
import nz.org.riskscape.engine.SRIDSet;
import nz.org.riskscape.engine.Tuple;
import nz.org.riskscape.engine.query.TupleUtils;
import nz.org.riskscape.engine.relation.SpatialMetadata;
import nz.org.riskscape.engine.types.Nullable;
import nz.org.riskscape.engine.types.Referenced;
import nz.org.riskscape.engine.types.Struct;
import nz.org.riskscape.engine.types.Struct.StructMember;
import nz.org.riskscape.engine.types.Type;
import nz.org.riskscape.engine.types.TypeProblems;
import nz.org.riskscape.engine.types.Types;
import nz.org.riskscape.problem.ResultOrProblems;

/**
 * Projects a tuple by modifying it's geometry in place to have a specific srid, as well as replacing the
 * {@link SpatialMetadata} that the relation produces to match.
 *
 * Note: This modifies the tuple in place, and doesn't clone either the tuple or the geometry that's modified.  This is
 * to support efficient modification on source datasets, where the tuples are being handed over.  This behaviour might
 * not be wanted in a querying situation.
 */
public class ForceSridProjection implements Projection {

  @RequiredArgsConstructor
  protected class ForceSridProjector implements Projector {

    private final StructMember sourceGeometryMember;
    @Getter
    private final Struct sourceType;
    private final StructMember projectedGeometryMember;
    @Getter
    private final Struct producedType;

    @Override
    public Tuple apply(Tuple t) {
      // we modify the tuple in place - this projection is meant to be used to assign an srid to an otherwise
      // anonymous relation
      Geometry geom = t.fetch(sourceGeometryMember);
      Object[] newValues = t.toArray();
      Tuple projected = Tuple.ofValues(producedType, newValues);
      if (geom != null) {
        // we could use geom.setSRID() here easy enough, but this doesn't update the GeometryFactory.
        // This means any new Geometry derived from this Geometry will still have an invalid SRID set,
        // e.g. taking the Geometry's centroid. The only way to set the factory is to create a new Geometry
        projected.set(projectedGeometryMember, factory.createGeometry(geom));
      }
      return projected;
    }

    @Override
    public Map<List<StructMember>, List<StructMember>> getDirectMapping() {
      return sourceType.getMembers().stream().collect(
          Collectors.toMap(
            (m) -> Arrays.asList(m),
            (m) -> Arrays.asList(m)
          ));
    }

    @Override
    public Optional<Function<SpatialMetadata, SpatialMetadata>> getSpatialMetadataMapper() {
      return Optional.of((spatialMetadata) -> {
        return new SpatialMetadata(crs, projectedGeometryMember);
      });
    }
  }

  public ForceSridProjection(CoordinateReferenceSystem newCrs, SRIDSet set) {
    this.srid = set.get(newCrs);
    this.crs = newCrs;
    this.factory = set.getGeometryFactory(newCrs);
  }

  private final int srid;
  private final CoordinateReferenceSystem crs;
  private final GeometryFactory factory;

  @Override
  public ResultOrProblems<Struct> projectType(Struct source) {
    return ResultOrProblems.of(source);
  }

  @Override
  public ResultOrProblems<Projector> getProjectionFunction(Struct sourceType) {
    StructMember sourceGeomMember = null;
    try {
      sourceGeomMember = TupleUtils.findRequiredGeometryMember(sourceType);
    } catch (RiskscapeException ex) {
      // TupleUtils.findRequiredGeometryMember throws RiskscapeException if there is no geometry found
      return ResultOrProblems.failed(TypeProblems.get().structMustHaveMemberType(Types.GEOMETRY, sourceType));
    }

    // we extract the actual geometry type out of a referenced, because you can't re-wrap a referenced
    // but only if the source is referened
    Type sourceGeomType = sourceGeomMember.getType()
        .findAllowNull(Referenced.class)
        .map(Referenced::getUnderlyingType)
        .orElse(sourceGeomMember.getType());

    Struct projectedType = sourceType.addOrReplace(
        sourceGeomMember.getKey(),
        // we need to take care to keep any nullable wrapping
        Referenced.ofNullable(Nullable.ifTrue(Nullable.is(sourceGeomMember.getType()), sourceGeomType), crs)
    );

    StructMember projectedGeomMember = TupleUtils.findRequiredGeometryMember(projectedType);

    return ResultOrProblems.of(
        new ForceSridProjector(sourceGeomMember, sourceType, projectedGeomMember, projectedType));
  }

}
