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

import java.io.IOException;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;

import nz.org.riskscape.engine.Tuple;
import nz.org.riskscape.engine.io.TupleReader;
import nz.org.riskscape.engine.relation.TupleIterator;
import nz.org.riskscape.engine.types.Struct;

/**
 * Consolidates a list of {@link TupleReader}s to always return the min value first as per the {@link Comparator}.
 * Will produce spurious results if the underlying {@link TupleReader}s aren't producing sorted results via the
 * same {@link Comparator}. This allows us to stream a set of sorted relations as though they were a single relation.
 */
public class MergeSortIterator implements TupleIterator {

  private final List<TupleReader> readers;
  private final boolean[] finished;
  private final Tuple[] peeked;

  private final Comparator<Tuple> comparator;
  private final Struct type;
  private Runnable onClose;

  /**
   * Create an {@link Iterator} over the given list of {@link TupleReader}s and using the given {@link Comparator} to
   * sort them
   */
  public MergeSortIterator(Comparator<Tuple> comparator, Struct type, List<TupleReader> readers, Runnable onClose) {
    this.type = type;
    this.readers = readers;
    this.peeked = new Tuple[readers.size()];
    this.finished = new boolean[readers.size()];
    this.comparator = comparator;
    this.onClose = onClose;
  }

  @Override
  public boolean hasNext() {
    fillPeeks();

    for (boolean finit : finished) {
      if (!finit) {
        return true;
      }
    }
    return false;
  }

  @Override
  public Tuple next() {
    // todo avoid rechecking after hasNext
    fillPeeks();

    int minIndex = -1;
    Tuple min = null;
    // TODO consider keeping a sort order so we can avoid having to search the whole list each time
    for (int i = 0; i < finished.length; i++) {
      if (finished[i]) {
        continue;
      }
      Tuple cmp = peeked[i];

      if (min == null || comparator.compare(min, cmp) > 0) {
        min = cmp;
        minIndex = i;
      }
    }

    peeked[minIndex] = null;
    return min;
  }

  @Override
  public void close() {
    this.onClose.run();
  }

  /**
   * Move through all the underlying streams, making sure they are either marked as finished or ready to be read.
   */
  private void fillPeeks() {
    for (int i = 0; i < finished.length; i++) {
      if (finished[i]) {
        continue;
      }

      if (peeked[i] == null) {
        Tuple read;
        try {
          read = readers.get(i).read(type);
        } catch (IOException e) {
          throw new RuntimeException("Underlying reader threw an exception", e);
        }

        if (read == null) {
          finished[i] = true;
        } else {
          peeked[i] = read;
        }
      }
    }
  }
}
