/*
 * 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 static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;

import org.junit.Before;
import org.junit.Test;

import com.google.common.collect.Lists;

import nz.org.riskscape.engine.Tuple;
import nz.org.riskscape.engine.pipeline.RealizedStep;
import nz.org.riskscape.engine.pipeline.SinkConstructor;
import nz.org.riskscape.engine.pipeline.sink.ListSink;
import nz.org.riskscape.engine.projection.FlatProjector;
import nz.org.riskscape.engine.projection.Projector;
import nz.org.riskscape.engine.relation.ListRelation;
import nz.org.riskscape.engine.relation.TupleIterator;
import nz.org.riskscape.engine.restriction.Restrictor;
import nz.org.riskscape.engine.sched.Page.ReadOnlyPage;
import nz.org.riskscape.engine.task.ChainTask;
import nz.org.riskscape.engine.task.ReturnState;
import nz.org.riskscape.engine.types.Struct;

/**
 * Covers some of the functional aspects of the ChainTask, without testing some of the edge cases around buffer
 * management
 */
public class ChainTaskTest extends BaseTaskTest<ChainTask> {

  public ChainTaskTest() {
    super(ChainTask.class);
    longs = new ListRelation(struct, longs(1, 5));
  }

  @Override @Before
  public void fillInput() {
    super.fillInput();
  }

  Restrictor evens = new Restrictor() {

    @Override
    public boolean test(Tuple t) {
      Long integer = t.fetch("value");
      return integer.longValue() % 2 == 0;
    }

    @Override
    public Struct getSourceType() {
      return struct;
    };
  };

  Restrictor threes = new Restrictor() {

    @Override
    public boolean test(Tuple t) {
      Long integer = t.fetch("value");
      return integer.longValue() % 3 == 0;
    }

    @Override
    public Struct getSourceType() {
      return struct;
    };
  };

  Projector doubleIt = new Projector() {

    @Override
    public Tuple apply(Tuple t) {
      Long integer = t.fetch("value");
      return Tuple.ofValues(struct, integer.longValue() * 2);
    }

    @Override
    public Struct getSourceType() {
      return struct;
    }

    @Override
    public Struct getProducedType() {
      return struct;
    }
  };

  AtomicLong nPowersCloseCounter = new AtomicLong();

  FlatProjector nPowers = new FlatProjector() {

    @Override
    public Struct getSourceType() {
      return struct;
    }

    @Override
    public Struct getProducedType() {
      return struct;
    }

    @Override
    public TupleIterator apply(Tuple tuple) {
      Long integer = tuple.fetch("value");
      List<Tuple> tuples = Lists.newArrayList();
      for (int i = 0; i < integer; i++) {
        tuples.add(Tuple.ofValues(struct, integer + (integer * i)));
      }
      return TupleIterator.wrapped(tuples.iterator(), Optional.of(() -> nPowersCloseCounter.incrementAndGet()));
    }

  };

  ChainTask chain;

  @Test
  public void testBasicRestriction() {
    createTask(newStep("evens", evens));

    assertEquals(ReturnState.COMPLETE, chain.run());
    assertEquals(Arrays.asList(2L, 4L), collect(chain));

    // the toString is used in debug logs, so we want to ensure that it's using the step name (not impl)
    assertThat(chain.toString(), containsString("ChainTask-1(steps=evens, input="));
  }

  @Test
  public void testBasicProjection() {
    createTask(newStep("doubleit", doubleIt));

    assertEquals(ReturnState.COMPLETE, chain.run());
    assertEquals(Arrays.asList(2L, 4L, 6L, 8L, 10L), collect(chain));
  }

  @Test
  public void testRestrictThenProject() {
    createTask(
      newStep("evens", evens),
      newStep("doubleit", doubleIt)
    );

    assertEquals(ReturnState.COMPLETE, chain.run());
    assertEquals(Arrays.asList(4L, 8L), collect(chain));
  }

  @Test
  public void testProjectThenRestrict() {
    createTask(
        newStep("doubleit", doubleIt),
        newStep("threes", threes)
    );

    assertEquals(ReturnState.COMPLETE, chain.run());
    assertEquals(Arrays.asList(6L), collect(chain));
  }

  @Test
  public void testFlatProject() {
    createTask(
        newStep("nPowers", nPowers)
    );

    assertEquals(ReturnState.COMPLETE, chain.run());

    assertEquals(Arrays.asList(
        1L,
        2L, 4L,
        3L, 6L, 9L,
        4L, 8L, 12L, 16L,
        5L, 10L, 15L, 20L, 25L
    ), collect(chain));

    assertEquals(5L, nPowersCloseCounter.get());
  }

  @Test
  public void testRestrictThenFlatProject() {

    createTask(
        newStep("evens", evens),
        newStep("nPowers", nPowers)
    );
    assertEquals(ReturnState.COMPLETE, chain.run());


    assertEquals(Arrays.asList(
        2L, 4L,
        4L, 8L, 12L, 16L
    ), collect(chain));

    assertEquals(2L, nPowersCloseCounter.get());
  }

  @Test
  public void testFlatProjectThenRestrict() {
    createTask(
      newStep("nPowers", nPowers),
      newStep("evens", evens)
    );

    assertEquals(ReturnState.COMPLETE, chain.run());
    assertEquals(Arrays.asList(
        2L, 4L,
        6L,
        4L, 8L, 12L, 16L,
        10L, 20L
    ), collect(chain));

    assertEquals(5L, nPowersCloseCounter.get());
  }

  @Test
  public void testTransformFlatProjectWithEmptiesThenRestrict() {

    // discards default page
    input = new LinkedListBuffer();
    longs = ListRelation.ofValues(1L, 0L, 4L, 0L, 5L);
    fill(input, longs.iterator());

    createTask(
        newStep("doubleit", doubleIt),
        newStep("nPowers", nPowers),
        newStep("threes", threes)
    );
    assertEquals(ReturnState.COMPLETE, chain.run());

    assertEquals(Arrays.asList(
        24L, 48L,
        30L, 60L, 90L
    ), collect(chain));

    assertEquals(5L, nPowersCloseCounter.get());
  }

  @Test
  public void closeWillCloseAnyUnFinishedTupleIteratorsThatAreInTheStack() throws Exception {
    output = new LinkedListBuffer(2, 1);
    createTask(
      newStep("nPowers", nPowers),
      newStep("austen-powers", nPowers)
    );

    assertEquals(ReturnState.OUTPUT_FULL, chain.run());

    assertEquals(Arrays.asList(
        1L, 2L
    ), collect(chain));

    chain.close();

    // two were  completed, one is on the stack and one is 'currentElement' that is half way through
    assertEquals(4L, nPowersCloseCounter.get());
  }

  @Test
  public void aFlatProjectionBeingInterruptedByAFullBufferCanBeResumedGL402() throws Exception {
    output = new LinkedListBuffer(2, 1);
    input = new LinkedListBuffer();
    longs = ListRelation.ofValues(10L, 11L);
    fill(input, longs.iterator());

    createTask(newStep("flatproject", nPowers));

    assertEquals(ReturnState.OUTPUT_FULL, chain.run());

    assertThat(
      collect(chain),
      contains(10L, 20L)
    );

    List<Long> collected = new ArrayList<>();
    while (chain.run() != ReturnState.COMPLETE) {
      collected.addAll(collect(chain));
    }

    assertThat(collected, contains(
      30L, 40L, 50L, 60L, 70L, 80L, 90L, 100L,
      11L, 22L, 33L, 44L, 55L, 66L, 77L, 88L, 99L, 110L
    ));
  }

  @Test
  public void canHaveASinkAtTheEndOfChain() {
    output = null;
    SinkConstructor constructor = ListSink.CONSTRUCTOR;
    createTask(
        newStep("doubleit", doubleIt),
        newStep("sink", constructor)
    );

    ListSink sink = (ListSink) chain.getLastOperation().op;

    assertEquals(ReturnState.COMPLETE, chain.run());
    assertEquals(
      Arrays.asList(2L, 4L, 6L, 8L, 10L),
      sink.getTuples().stream().map(t -> t.fetch("value")).collect(Collectors.toList())
    );
  }

  private List<Long> collect(ChainTask chainTask) {
    ReadOnlyPage page = output.read();
    List<Long> values = Lists.newArrayList();
    while (page.hasNext()) {
      Tuple tuple = page.next();
      values.add((Long) tuple.fetch("value"));
    }

    return values;
  }

  @Override
  public ChainTask createTask(RealizedStep... steps) {
    // to avoid diff noise
    chain = super.createTask(steps);
    return chain;
  }

}
