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

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import lombok.EqualsAndHashCode;
import lombok.Getter;
import nz.org.riskscape.engine.Engine;
import nz.org.riskscape.engine.i18n.ResourceClassLoader;

/**
 * Each {@link Plugin} has classes loaded from its own {@link DefaultPluginClassLoader}.  These should inherit from the
 * {@link Engine}'s class loader, so that the plugins can access the core classes.  Plugins can also depend on other
 * plugins, which allows classes for this plugin to be loaded/linked from another plugin's class loader.
 *
 * TODO add some integration tests for the plugin mechanism?
 */
@EqualsAndHashCode(of = {"jarUrl", "dependencies"}, callSuper = false)
public class PluginClassLoader extends URLClassLoader {

  /**
   * Returns a plugin class loader to use in test situations.  Likely to go bang if you try and load classes from it
   */
  public static PluginClassLoader newDummy() {
    try {
      return new PluginClassLoader(PluginClassLoader.class.getClassLoader(), new URL("file:///"));
    } catch (MalformedURLException e) {
      throw new IllegalStateException(e);
    }
  }

  // other plugin dependencies - this should be populated during engine bootstrapping
  @Getter
  private List<PluginClassLoader> dependencies;

  // flag to prevent classloader from being messed with post boostrapping
  private boolean frozen = false;

  private DefaultPluginDescriptor descriptor;

  // lazily create classloader for resources from the i18n directory
  private ResourceClassLoader i18nClassLoader;

  @Getter
  private final URL jarUrl;

  private static URL[] joinUrls(URL jarUrl, URL[] otherDependencies) {
    URL[] newUrls = new URL[otherDependencies.length + 1];
    newUrls[0] = jarUrl;
    System.arraycopy(otherDependencies, 0, newUrls, 1, otherDependencies.length);
    return newUrls;
  }

  /**
   * Create a new plugin class loader
   * @param jarUrl primary library that constitutes this plugin's code
   * @param dependencies Array of urls to subsidiary dependencies with own libraries and all exported libraries of
   * plugins that are required for this plugin.
   * @param engineClassLoader the parent class loader, expected to be the engine's class loader
   */
  public PluginClassLoader(ClassLoader engineClassLoader, URL jarUrl, URL... dependencies) {
    super(joinUrls(jarUrl, dependencies), engineClassLoader);
    this.jarUrl = jarUrl;
    this.dependencies = new LinkedList<>();
  }

  /**
   * Assign the {@link PluginDescriptor} that uses this class loader - this should be a strictly 1-1 relationship.
   */
  public void setPluginDescriptor(PluginDescriptor toSet) {
    if (this.descriptor != null) {
      throw new IllegalStateException("Can not set descriptor twice - this is effectively a final field");
    }
    if (!(toSet instanceof DefaultPluginDescriptor)) {
      throw new IllegalArgumentException("The default PluginClassLoader must be used with a DefaultPluginDescriptor");
    }
    DefaultPluginDescriptor dToSet = (DefaultPluginDescriptor) toSet;

    if (dToSet.getClassLoader() != this) {
      throw new IllegalStateException("Can not assign a descriptor that isn't assigned to this classloader itself");
    }

    this.descriptor = dToSet;
  }

  /**
   * Add a plugin dependency to this plugin.  The given class loader will be searched for classes once loading fails
   * from this classloader's resources, the engine's classloader, and finally the system class path.
   */
  public void addDependency(PluginClassLoader classLoader) {
    if (frozen) {
      throw new IllegalStateException("you can't add plugin dependencies once the class loader is frozen");
    }
    this.dependencies.add(classLoader);
  }

  /**
   * Prevent further plugins from being added to this one, just in case... who knows what that will do?
   */
  public void freeze() {
    frozen = true;
  }

  @Override
  protected synchronized Class<?> loadClass(String name, boolean resolve)
      throws ClassNotFoundException {

    // First, check if the class has already been loaded
    Class<?> c = findLoadedClass(name);

    if (c == null) {
      try {
        // checking local
        c = findClass(name);
      } catch (ClassNotFoundException | SecurityException e) {
        c = loadClassFromEngineOrDependencies(name, resolve);
      }
    }

    if (resolve) {
      resolveClass(c);
    }

    return c;
  }

  /**
   * Attempt to load a class directly from this classloader's classpath, without delegating the search anywhere else.
   * This is used by other PluginClassLoader's to search for their dependencies, and is never called from `this`.
   *
   * NB it does end up searching the engine's classpath as well, which is harmless but wasteful.  I'm a little shy of
   * changing this class loader too much, due to general ignorance and inexperience with implementing custom
   * classloaders
   */
  protected synchronized Class<?> loadClassLocally(String name, boolean resolve)
      throws ClassNotFoundException {

    // First, check if the class has already been loaded
    Class<?> c = findLoadedClass(name);

    if (c == null) {
       // checking local
      try {
        c = findClass(name);
      } catch (ClassNotFoundException e) {
        // this skips the search on the engine class loader, as it's assumed we've already searched that class loader -
        // all plugins should be sharing the same engine class loader and this method is used from our dependents as
        // part of their own class loader search
        c = loadClassFromDependencies(name, resolve);
      }
    }

    if (resolve) {
      resolveClass(c);
    }

    return c;
  }

  /**
   * Search for a class from the engine class loader, falling back to our plugin dependencies
   *
   * In the future, we may decide to 'export' specific JARs from a plugin to others, and at that point we should
   * probably prioritize the dependency's exported jars over the engine ones (otherwise I would worry about the impact /
   * confusion caused)
   */
  private Class<?> loadClassFromEngineOrDependencies(String name, boolean resolve)
      throws ClassNotFoundException {
    // checking parent
    // This call to loadClass may eventually call findClass
    // again, in case the parent doesn't find anything.
    Class<?> c;
    try {
      // this looks up from parent, which should be the engine class loader.  This engine class loader in turn delegates
      // to the system and then bootstrapping classloader
      c = super.loadClass(name, resolve);
    } catch (ClassNotFoundException e) {
      c = loadClassFromDependencies(name, resolve);
    }

    return c;
  }

  /**
   * Search through dependencies to see if they have this class
   */
  private Class<?> loadClassFromDependencies(String name, boolean resolve) throws ClassNotFoundException {
    for (PluginClassLoader pluginClassLoader : dependencies) {
      try {
        return pluginClassLoader.loadClassLocally(name, resolve);
      } catch (ClassNotFoundException e) {
      }
    }
    throw new ClassNotFoundException(name);
  }


  /**
   * Get a resource from local resources, engine resources, then falling back to plugin resources
   */
  @Override
  public URL getResource(String name) {
    URL url = findResource(name);
    if (url == null) {
      url = super.getResource(name);
    }
    if (url == null) {
      for (PluginClassLoader pluginClassLoader : dependencies) {
        // uses findResource to avoid searching the engine class loader again
        url = pluginClassLoader.findResource(name);
        if (url != null) {
          return url;
        }
      }
    }
    return url;
  }

  @Override
  public Enumeration<URL> getResources(String name) throws IOException {
    final List<URL> collectedUrls = new LinkedList<URL>();

    // local urls first
    drainEnum(findResources(name), collectedUrls);

    // then engine resources
    drainEnum(getParent().getResources(name), collectedUrls);

    // falling back to dependencies
    // NB we may want to make dependencies take precedence over engine?
    for (PluginClassLoader pluginClassLoader : dependencies) {
      // we use findResources here to avoid doubling up on any thing that come from the engine class loader
      drainEnum(pluginClassLoader.findResources(name), collectedUrls);
    }

    return new Enumeration<URL>() {
      Iterator<URL> iter = collectedUrls.iterator();

      @Override
      public boolean hasMoreElements() {
        return iter.hasNext();
      }

      @Override
      public URL nextElement() {
        return iter.next();
      }
    };
  }

  private void drainEnum(Enumeration<URL> urlsMaybeNull, List<URL> collect) {
    if (urlsMaybeNull == null) {
      return;
    }
    while (urlsMaybeNull.hasMoreElements()) {
      collect.add(urlsMaybeNull.nextElement());
    }
  }

  @Override
  public InputStream getResourceAsStream(String name) {
    URL url = getResource(name);
    try {
      return url != null ? url.openStream() : null;
    } catch (IOException e) {
    }
    return null;
  }

  @Override
  public String toString() {
    return String.format(
        "PluginClassLoader(%s, urls=%s, dependencies=%s)",
        descriptor.getPluginId(),
        getURLs(),
        dependencies
    );
  }

  /**
   * @return a lazily-created ResourceClassLoader that is configured to load resources (and not classes) from the
   * i18n directory next to the code plugin code.
   */
  public ResourceClassLoader getI18nResourceLoader() {
    if (i18nClassLoader == null) {
      i18nClassLoader = new ResourceClassLoader(jarUrl);
    }

    return i18nClassLoader;
  }

}
