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

import java.net.URI;
import java.nio.file.Paths;
import java.util.Set;
import java.util.function.Consumer;

import org.geotools.api.referencing.crs.CoordinateReferenceSystem;
import org.geotools.referencing.crs.DefaultGeographicCRS;

import com.codahale.metrics.MetricRegistry;
import com.google.common.collect.Sets;

import lombok.Getter;
import lombok.Setter;
import nz.org.riskscape.config.Config;
import nz.org.riskscape.engine.bind.BindingContext;
import nz.org.riskscape.engine.bind.DefaultBindingContext;
import nz.org.riskscape.engine.bind.UserDefinedParameter;
import nz.org.riskscape.engine.data.Bookmark;
import nz.org.riskscape.engine.data.Bookmarks;
import nz.org.riskscape.engine.data.DefaultBookmarks;
import nz.org.riskscape.engine.function.IdentifiedFunction;
import nz.org.riskscape.engine.geo.GeometryValidation;
import nz.org.riskscape.engine.model.IdentifiedModel;
import nz.org.riskscape.engine.pipeline.DefaultExecutionContext;
import nz.org.riskscape.engine.pipeline.ExecutionContext;
import nz.org.riskscape.engine.rl.RealizationContext;
import nz.org.riskscape.engine.typeset.TypeSet;
import nz.org.riskscape.engine.typexp.DefaultTypeBuilder;
import nz.org.riskscape.engine.typexp.TypeBuilder;
import nz.org.riskscape.problem.Problem;
import nz.org.riskscape.problem.ProblemSink;

public class DefaultProject extends DefaultIdentifiedLocator implements Project {

  @Getter
  private final Engine engine;

  @Getter
  private final SRIDSet sridSet;

  @Getter
  private Config config;

  @Getter @Setter
  private CoordinateReferenceSystem defaultCrs = DefaultGeographicCRS.WGS84;

  @Setter
  private URI relativeTo;

  @Setter
  private URI outputBaseLocation;

  @Getter
  private GeometryValidation geometryValidation;

  @Getter
  private final Bookmarks bookmarks = put(new DefaultBookmarks());

  @Getter
  private final FunctionSet functionSet = put(new DefaultFunctionSet());

  @Getter
  private final TypeSet typeSet;

  @Getter
  private final IdentifiedCollection<IdentifiedModel> identifiedModels =
    put(new IdentifiedCollection.Base<>(IdentifiedModel.class));

  @Getter
  private final IdentifiedCollection<UserDefinedParameter> parameterTemplates =
    put(new IdentifiedCollection.Base<>(UserDefinedParameter.class));

  private TypeBuilder typeBuilder;

  public DefaultProject(Engine engine, Config config) {
    this.engine = engine;
    this.typeSet = put(new TypeSet(engine.getTypeRegistry()));
    this.sridSet = new SRIDSet(getProblemSink());
    this.config = config;
    // default geometry validation to fix automatically or bail if can't fix
    setGeometryValidation(GeometryValidation.ERROR);
  }

  @Override
  public void validate(ExecutionContext context, Consumer<Problem> problemConsumer) {
    typeSet.validate(problemConsumer);
    functionSet.validate(context, problemConsumer);
    bookmarks.validate(context, problemConsumer);
  }

  @Override
  public BindingContext newBindingContext() {
    return new DefaultBindingContext(this, getProblemSink());
  }

  @Override
  public void add(Bookmark bookmark) {
    bookmarks.add(bookmark);
  }

  @Override
  public void add(IdentifiedFunction function) {
    functionSet.add(function);
  }

  @Override
  public URI getOutputBaseLocation() {
    if (outputBaseLocation != null) {
      return outputBaseLocation;
    }
    return getRelativeTo().resolve("output/");
  }

  @Override
  public TypeBuilder getTypeBuilder() {
    if (typeBuilder == null) {
      typeBuilder = new DefaultTypeBuilder(getTypeSet());
    }

    return typeBuilder;
  }

  @Override
  public RealizationContext newRealizationContext() {
    return new DefaultRealizationContext(this, new MetricRegistry(), newBindingContext(), getProblemSink());
  }

  @Override
  public ExecutionContext newExecutionContext(ProblemSink problemSink) {
    return new DefaultExecutionContext(this, problemSink);
  }

  @Override
  public URI getRelativeTo() {
    if (relativeTo == null) {
      // if relativeTo has not been set we should be relative to the current working directory.
      return Paths.get("").toUri();
    }
    return relativeTo;
  }

  @Override
  public boolean hasCollectionOf(Class<? extends Identified> identifiedClass) {
    return super.hasCollectionOf(identifiedClass) || getEngine().hasCollectionOf(identifiedClass);
  }

  @Override
  public <T extends Identified> IdentifiedCollection<T> getCollectionByClass(Class<T> collectionClass) {

    if (engine.hasCollectionOf(collectionClass)) {
      return engine.getCollectionByClass(collectionClass);
    }

    return super.getCollectionByClass(collectionClass);
  }

  @Override
  public Set<Class<? extends Identified>> getCollectionClasses() {
    return Sets.union(super.getCollectionClasses(), engine.getCollectionClasses());
  }

  @Override
  public final ProblemSink getProblemSink() {
    return engine.getProblemSink();
  }

  @Override
  public void setGeometryValidation(GeometryValidation mode) {
    geometryValidation = mode;
    sridSet.setValidationPostReproject(mode);
  }
}
