/*
 * 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.
 */
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package nz.org.riskscape.engine.plugin;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;

import lombok.Getter;
import nz.org.riskscape.engine.Engine;
import nz.org.riskscape.engine.Project;
import nz.org.riskscape.engine.data.BookmarkResolver;
import nz.org.riskscape.engine.function.IdentifiedFunction;
import nz.org.riskscape.engine.model.Model;
import nz.org.riskscape.engine.resource.ResourceLoader;
import nz.org.riskscape.engine.types.Type;
import nz.org.riskscape.problem.Problem;
import nz.org.riskscape.problem.ProblemSink;

/**
 * A Riskscape Plugin.  So far, a riskscape plugin is used to help initialize an engine, the expectation being
 * that the plugin can supply an engine with types, functions and models etc.
 * <p>
 * Derived from the Nutch project's plugin system
 */
public abstract class Plugin {

  @Getter
  private final PluginDescriptor descriptor;

  public String getId() {
    return descriptor.getPluginId();
  }

  public Plugin(PluginDescriptor pDescriptor) {
    Objects.requireNonNull(pDescriptor, "pDescriptor must not be null");
    this.descriptor = pDescriptor;
  }

  /**
   * Will be invoked on plugin start up and before {@link #initializeEngine(Engine, ProblemSink)} is called.
   * Gives plugins a change to bootstrap some expensive global state.
   */
  protected void startUp(Map<String, List<String>> settings) throws PluginRuntimeException {
  }

  public void startUp(Map<String, List<String>> settings, ProblemSink terminal) {
    startUp(settings);
  }

  /**
   * Shutdown the plugin.  Might be called when the engine is destroyed.
   */
  public void shutDown() throws PluginRuntimeException {
  }

  @Override
  protected void finalize() throws Throwable {
    super.finalize();
    shutDown();
  }

  /**
   * Initialize the {@link Engine} with any services that are provided by this Plugin. For example:
   * - {@link Model}s
   * - {@link BookmarkResolver}s
   * - {@link ResourceLoader}s
   *
   * @param engine the engine to populate with things.
   * @return any non-fatal warnings or errors generated that can be shown to the user
   */
  public abstract List<Problem> initializeEngine(Engine engine);

  /**
   * Initialize the {@link Engine} with any services that are provided by this Plugin. For example:
   * - {@link Model}s
   * - {@link BookmarkResolver}s
   * - {@link ResourceLoader}s
   *
   * Use this method over {@link #initializeEngine(Engine)} to report problems immediately, which can be a better way
   * to give feedback for the user, especially where things can happen over a greater period of time.
   *
   * @param engine the engine to populate with things.
   * @param problemSink a place to report any non-fatal warnings or errors generated that can be shown to the user
   */
  public void initializeEngine(Engine engine, ProblemSink problemSink) {
    List<Problem> problems = initializeEngine(engine);
    problems.forEach(p -> problemSink.log(p));
  }

  /**
   * Fill a {@link Project} with goodies, usually by scanning through the Project's Config.  For example:
   * - {@link Type}s
   * - {@link IdentifiedFunction}s
   * - etc
   * @param project the project to populate
   * @param engine containing services that may be required.
   * @return any non-fatal warnings or errors generated that can be shown to the user
   */
  public List<Problem> initializeProject(Project project, Engine engine) {
    return Collections.emptyList();
  }

  /**
   * Query a {@link Plugin} to see if it supports the given 'service provider interface'.  Support is currently limited
   * to interfaces defined by the core engine classes - there is no support for plugins defining their own (yet) as this
   * requires some class loader magic that we don't yet need.
   *
   * The current implementation, which isn't likely to last, queries the Plugin object itself to see if it implements
   * the given interface.
   *
   * The plan for the future might be to move things like resolvers and models etc in to SPI specific things to more
   * precisely control the way the engine is built/augmented
   *
   * @param spi the interface to look for in this plugin
   * @return an object implementing the spi if it is supported, or {@link Optional#empty()} if this spi is not supported
   * by the {@link Plugin}.
   * @deprecated use the new ExtensionPoint API instead.  We should start moving Features across to that as and when we
   * touch them.
   */
  @Deprecated
  public <T> Optional<T> supportsFeature(Class<T> spi) {
    if (spi.isAssignableFrom(this.getClass())) {
      return Optional.ofNullable(spi.cast(this));
    } else {
      return Optional.empty();
    }
  }

  /**
   * @return the classloader this plugin provides for loading i18n resources.  This method should be used in preference
   * to the descriptor's default implementation in case the plugin wants to customize the class loader in someway.
   */
  public ClassLoader getI18nClassLoader() {
    return descriptor.getI18nClassLoader();
  }

  /**
   * Returns a list of {@link PluginFeature} classes advertised by this {@link Plugin} as possible extension points.
   * While most extension points will be implemented in the core of the engine, it is possible for plugins to advertise
   * their own for other dependent plugins to implement.
   */
  public List<Class<? extends PluginFeature>> getExtensionPoints() {
    return Collections.emptyList();
  }

  /**
   * @return a list of {@link PluginFeature}s implemented by this {@link Plugin}
   */
  public List<PluginFeature> getFeatures() {
    return Collections.emptyList();
  }
}
