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

import java.util.AbstractList;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.NoSuchElementException;

import nz.org.riskscape.engine.Tuple;
import nz.org.riskscape.engine.function.ExpensiveResource;
import nz.org.riskscape.engine.relation.Relation;
import nz.org.riskscape.problem.ProblemSink;

/**
 * Allows a {@link Relation} to be treated like a List in a pipeline.
 * Mostly this is to allow relation data to be dynamically loaded from multiple different
 * sources, i.e. read a CSV file that points to other CSV files. Typically in a pipeline,
 * this will look something like:
 * `select({*, to_list(bookmark(foo)) as relation_backed_list }) -> unnest(relation_backed_list)`
 *
 * Warning: some basic list operations can be slow for a RelationBackedList, especially
 * if the relation is large. Some basic list operations are unsupported (i.e. modifying the
 * list), although lists typically aren't modified in a pipeline (instead, a new list is created).
 */
public class RelationBackedList extends AbstractList<Tuple> {

  private final Relation relation;
  private ExpensiveResource<Integer> exactSize;

  public RelationBackedList(Relation relation, ProblemSink sink) {
    this.relation = relation;
    // relation.size() is only the "rough" size, so can't be trusted (and isn't supported
    // for all relation types). Count the tuples by hand, if needed, although this could take a while
    this.exactSize = new ExpensiveResource<Integer>(sink, "relation-size", () -> {
      int size = 0;
      Iterator<Tuple> iterator = iteratorWithWarningsSuppressed();
      while (iterator.hasNext()) {
        size++;
        iterator.next();
      }
      return size;
    });
  }

  /**
   * @return a tuple iterator that won't log any warnings (but will throw errors)
   */
  private Iterator<Tuple> iteratorWithWarningsSuppressed() {
    if (relation.hasSkipOnInvalid()) {
      // suppress logs for invalid tuples for internal list operations, e.g. peeking at first tuple
      // or calculating the list size. This avoids logging the same warning repeatedly - we'll still
      // get the warning when we try to iterate over the list items
      return relation.skipInvalid(ProblemSink.DEVNULL).iterator();
    } else {
      // don't change the underlying relation's behaviour - blow up if the relation has a bad tuple.
      // List-based operations, like unnest(), may have short-circuits when list.isEmpty()/.size() == 0.
      // If the list *only* contains invalid tuples, we want to hit an error - we don't want these
      // short-circuits to treat the list as empty
      return relation.iterator();
    }
  }

  @Override
  public Iterator<Tuple> iterator() {
    return relation.iterator();
  }

  /**
   * Warning: accessing a specific item in RelationBackedList can be slow, as it requires
   * iterating through all the tuples in the relation up to the specific index.
   */
  @Override
  public Tuple get(int index) {
    try {
      int ctr = 0;
      Iterator<Tuple> iter = iterator();
      while (ctr != index) {
        ctr++;
        iter.next();
      }
      return iter.next();

    } catch (NoSuchElementException ex) {
      // make the exception more list-like, and less iterator-like
      throw new IndexOutOfBoundsException("Bad index: " + index);
    }
  }

  /**
   * Note that size() only includes the valid tuples in the relation.
   * Warning: getting the size of a RelationBackedList can be slow, as it requires iterating through
   * *all* the tuples in the relation in order to work out the exact size.
   */
  @Override
  public int size() {
    return exactSize.get();
  }

  @Override
  public boolean isEmpty() {
    // it's a lot quicker to check the iterator than the relation size()
    return !iteratorWithWarningsSuppressed().hasNext();
  }

  @Override
  public void add(int index, Tuple element) {
    throw new UnsupportedOperationException();
  }

  @Override
  public boolean add(Tuple element) {
    throw new UnsupportedOperationException();
  }

  @Override
  public boolean addAll(Collection<? extends Tuple> c) {
    throw new UnsupportedOperationException();
  }

  @Override
  public void sort(Comparator<? super Tuple> c) {
    throw new UnsupportedOperationException();
  }
}
