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

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.ResourceBundle;
import java.util.function.BiPredicate;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;

/**
 * ClassLoader for use with building {@link ResourceBundle}s that uses an explicit search path for finding resources
 * for use with {@link ResourceBundleControl} to control the order with which values from bundles over-write each other.
 *
 * Maintains a list of class loaders and gives methods for adding new ones at various points to adjust precedence order.
 * Precedence is based on list order where list item 0 is highest to list item n lowest.
 *
 * Also adds a new {@link #getResourcesByPrecedence(String)} method to allow the control file to create a
 * {@link MergedPropertiesResourceBundle} with application-defined precedence.  This allows us to make sure that things
 * like default message can be replaced and redefined by plugins and then again by explicit i18n folders on the user's
 * installed system.
 *
 */
@Slf4j
public class I18nClassLoader extends ClassLoader {

  @Data
  private static class Pair {
    final Object owner;
    final ClassLoader loader;
  }

  private final List<Pair> searchList = new ArrayList<>();

  /**
   * Inserts a class loader at the end of the list(lowest precedence).
   *
   * @param owner
   * @param loader
   */
  public void append(Object owner, ClassLoader loader) {
    Pair pair = new Pair(owner, loader);
    searchList.add(pair);
    invalidateCache(pair);
  }

  /**
   * Inserts a class loader at the head of the list(highest precedence).
   *
   * @param owner
   * @param loader
   */
  public void unshift(Object owner, ClassLoader loader) {
    Pair pair = new Pair(owner, loader);
    searchList.add(0, pair);
    invalidateCache(pair);
  }

  /**
   * Inserts a class loader pair before the pair matched by searchMethod.
   *
   * If searchMethod does not match any existing class loader pairs then no class loader is inserted and
   * this method returns false.
   *
   * @param owner
   * @param loader
   * @param searchMethod to match pair to insert before
   * @return true is class loader pair was added, false otherwise.
   */
  public boolean insertBefore(Object owner, ClassLoader loader, BiPredicate<Object, ClassLoader> searchMethod) {
    return insert(true, owner, loader, searchMethod);
  }

  /**
   * Similar to {@link #insertBefore(java.lang.Object, java.lang.ClassLoader, java.util.function.BiPredicate)
   * but class loader is added after the pair matched by searchMethod.
   */
  public boolean insertAfter(Object owner, ClassLoader loader, BiPredicate<Object, ClassLoader> searchMethod) {
    return insert(false, owner, loader, searchMethod);
  }

  private boolean insert(boolean before, Object owner, ClassLoader loader,
      BiPredicate<Object, ClassLoader> searchMethod) {
    for (int i = 0; i < searchList.size(); i++) {
      Pair pair = searchList.get(i);
      if (searchMethod.test(pair.owner, pair.loader)) {
        Pair newPair = new Pair(owner, loader);
        searchList.add(
            before ? i: i + 1,
            newPair
          );

        invalidateCache(newPair);
        return true;
      }
    }
    return false;
  }

  @Override
  protected Class<?> findClass(String name) throws ClassNotFoundException {
    for (Pair pair : searchList) {
      try {
        return pair.loader.loadClass(name);
      } catch (ClassNotFoundException ex) {}
    }

    throw new ClassCastException(name + " not found among any of " + searchList);
  }

  @Override
  public URL getResource(String name) {
    for (Pair pair : searchList) {
      URL resource = pair.loader.getResource(name);
      if (resource != null) {
        return resource;
      }
    }
    return null;
  }

  /**
   * @return a list of resource {@link URL}s that match the given name, in order that they were found in the search
   * list.  Only returns up to one {@link URL} per class-loader.
   */
  public List<URL> getResourcesByPrecedence(String name) {
    List<URL> allUrls = new ArrayList<>();

    for (Pair pair : searchList) {
      URL subResource= pair.loader.getResource(name);
      if (subResource != null) {
        allUrls.add(subResource);
      }
    }

    log.debug("Search for {} found {}", name, allUrls);

    return allUrls;
  }

  @Override
  public Enumeration<URL> getResources(String name) throws IOException {
    List<URL> allUrls = new ArrayList<>();

    for (Pair pair : searchList) {
      Enumeration<URL> subResources = pair.loader.getResources(name);
      while (subResources.hasMoreElements()) {
        allUrls.add(subResources.nextElement());
      }
    }

    return Collections.enumeration(allUrls);
  }

  private void invalidateCache(Pair pair) {
    log.debug("Invalidating resource bundle cache for {} because of {}", this, pair);
    ResourceBundle.clearCache(this);
  }

}
