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

import java.util.List;
import java.util.stream.Collectors;

import lombok.RequiredArgsConstructor;
import nz.org.riskscape.engine.Tuple;
import nz.org.riskscape.engine.output.PipelineJobContext;
import nz.org.riskscape.engine.pipeline.Collector;
import nz.org.riskscape.engine.pipeline.Sink;
import nz.org.riskscape.engine.pipeline.SinkConstructor;
import nz.org.riskscape.engine.task.ChainTask;
import nz.org.riskscape.engine.task.SinkTask;
import nz.org.riskscape.problem.ResultOrProblems;

/**
 * An unbounded {@link Sink} that receives results for accumulation, intended for use at the end of a
 * {@link ChainTask} where a chain can feed multiple groupings, or, in a standalone {@link SinkTask} where usually
 * (so far) a single collection is fed from something other than a chain - perhaps another grouping.
 */
@SuppressWarnings("rawtypes")
public class AccumulatorSink implements Sink {

  @RequiredArgsConstructor
  public static class Constructor implements SinkConstructor {

    private final List<Collector<?>> collectors;
    @Override
    public ResultOrProblems<Sink> newInstance(PipelineJobContext jobContext) {
      return ResultOrProblems.of(new AccumulatorSink(collectors));
    }

  }
  private final Collector[] collectors;
  private final Object[] accumulators;
  private boolean finished = false;

  public AccumulatorSink(List<Collector<?>> collectors) {
    this.collectors = collectors.toArray(new Collector[0]);
    this.accumulators = collectors.stream().map(Collector::newAccumulator).collect(Collectors.toList()).toArray();
  }
  @Override
  public boolean accept(Tuple tuple) {
    for (int i = 0; i < collectors.length; i++) {
      collectors[i].accumulate(accumulators[i], tuple);
    }

    return true;
  }

  /**
   * Returns the accumulator for a given collector. This clears the accumulator for the sink
   * (so that any tuples associated with the accumulator can eventually be garbage collected),
   * so should only be called when the sink is finished.
   */
  public Object getAndClearAccumulator(Collector forCollector) {
    if (!finished) {
      throw new IllegalStateException("Cannot clear while accumulating still in progress!");
    }

    for (int i = 0; i < collectors.length; i++) {
      if (collectors[i] == forCollector) {
        Object accumulator = accumulators[i];
        accumulators[i] = null;
        return accumulator;
      }
    }

    return null;
  }

  @Override
  public void finish() {
    finished = true;
  }

  @Override
  public boolean isUnbounded() {
    return true;
  }

  @Override
  public boolean canAccept() {
    return true;
  }

}
