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

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

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

import com.google.common.collect.Lists;

import nz.org.riskscape.engine.ProjectTest;
import nz.org.riskscape.engine.Tuple;
import nz.org.riskscape.engine.rl.DefaultOperators;
import nz.org.riskscape.engine.sort.SortBy.Direction;
import nz.org.riskscape.engine.sort.TupleComparator.ProblemCodes;
import nz.org.riskscape.engine.types.Struct;
import nz.org.riskscape.engine.types.Types;
import nz.org.riskscape.problem.ResultOrProblems;
import nz.org.riskscape.problem.Problem.Severity;
import nz.org.riskscape.rl.ast.Expression;
import nz.org.riskscape.rl.ast.ExpressionProblems;

/**
 * Tests for the of Comparator<Tuple>.
 */
@SuppressWarnings("unchecked")
public class TupleComparatorTest extends ProjectTest {

  Struct tupleType = Struct.of("integer", Types.INTEGER, "floating", Types.FLOATING, "decimal", Types.DECIMAL)
      .add("text", Types.TEXT).add("date", Types.DATE);

  @Before
  public void setup() {
    this.project.getFunctionSet().insertFirst(DefaultOperators.INSTANCE);
  }

  @Test
  public void canCompareIntegerAscending() throws Exception {
    List<Tuple> input = Lists.newArrayList(
        Tuple.of(tupleType, "integer", null),
        Tuple.of(tupleType, "integer", 3),
        Tuple.of(tupleType, "integer", 1),
        Tuple.of(tupleType, "integer", 2));
    ResultOrProblems<Comparator<Tuple>> r = TupleComparator.createComparator(tupleType,
        new SortBy(toExpression("integer"), Direction.ASC),
        expressionRealizer);
    input.sort(r.get());
    assertThat(input, contains(
        Tuple.of(tupleType, "integer", null),
        Tuple.of(tupleType, "integer", 1),
        Tuple.of(tupleType, "integer", 2),
        Tuple.of(tupleType, "integer", 3)
    ));
  }

  @Test
  public void canCompareIntegerDecending() throws Exception {
    List<Tuple> input = Lists.newArrayList(
        Tuple.of(tupleType),
        Tuple.of(tupleType, "integer", 3),
        Tuple.of(tupleType, "integer", 1),
        Tuple.of(tupleType, "integer", 2));
    ResultOrProblems<Comparator<Tuple>> r = TupleComparator.createComparator(tupleType,
        new SortBy(toExpression("integer"), Direction.DESC),
        expressionRealizer);
    input.sort(r.get());
    assertThat(input, contains(
        Tuple.of(tupleType, "integer", 3),
        Tuple.of(tupleType, "integer", 2),
        Tuple.of(tupleType, "integer", 1),
        Tuple.of(tupleType)
    ));
  }

  @Test
  public void canCompareFloatAscending() throws Exception {
    List<Tuple> input = Lists.newArrayList(
        Tuple.of(tupleType),
        Tuple.of(tupleType, "floating", 3.5d),
        Tuple.of(tupleType, "floating", 1.1D),
        Tuple.of(tupleType, "floating", 2L));
    ResultOrProblems<Comparator<Tuple>> r = TupleComparator.createComparator(tupleType,
        new SortBy(toExpression("floating"), Direction.ASC),
        expressionRealizer);
    input.sort(r.get());
    assertThat(input, contains(
        Tuple.of(tupleType),
        Tuple.of(tupleType, "floating", 1.1d),
        Tuple.of(tupleType, "floating", 2L),
        Tuple.of(tupleType, "floating", 3.5d)
    ));
  }

  @Test
  public void canCompareDecimalAscending() throws Exception {
    List<Tuple> input = Lists.newArrayList(
        Tuple.of(tupleType),
        Tuple.of(tupleType, "decimal", 3.5d),
        Tuple.of(tupleType, "decimal", 1.1D),
        Tuple.of(tupleType, "decimal", 2L));
    ResultOrProblems<Comparator<Tuple>> r = TupleComparator.createComparator(tupleType,
        new SortBy(toExpression("decimal"), Direction.ASC),
        expressionRealizer);
    input.sort(r.get());
    assertThat(input, contains(
        Tuple.of(tupleType),
        Tuple.of(tupleType, "decimal", 1.1d),
        Tuple.of(tupleType, "decimal", 2L),
        Tuple.of(tupleType, "decimal", 3.5d)
    ));
  }

  @Test
  public void canCompareIntegerAscending_ThenDecimalAscending() throws Exception {
    List<Tuple> input = Lists.newArrayList(
        Tuple.of(tupleType),
        Tuple.of(tupleType, "integer", 1, "decimal", 2.0d),
        Tuple.of(tupleType, "integer", 1, "decimal", 4.0d),
        Tuple.of(tupleType, "integer", 1, "decimal", 3.0d));
    ResultOrProblems<Comparator<Tuple>> r = TupleComparator.createComparator(tupleType,
        new SortBy(toExpression("integer"), Direction.ASC).andThen(
            new SortBy(toExpression("decimal"), Direction.ASC)),
        expressionRealizer);
    input.sort(r.get());
    assertThat(input, contains(
        Tuple.of(tupleType),
        Tuple.of(tupleType, "integer", 1, "decimal", 2.0d),
        Tuple.of(tupleType, "integer", 1, "decimal", 3.0d),
        Tuple.of(tupleType, "integer", 1, "decimal", 4.0d)
    ));
  }

  @Test
  public void canCompareIntergerAscending_ThenDecimalDecending() throws Exception {
    List<Tuple> input = Lists.newArrayList(
        Tuple.of(tupleType),
        Tuple.of(tupleType, "integer", 1, "decimal", 2.0d),
        Tuple.of(tupleType, "integer", 1, "decimal", 4.0d),
        Tuple.of(tupleType, "integer", 1, "decimal", 3.0d));
    ResultOrProblems<Comparator<Tuple>> r = TupleComparator.createComparator(tupleType,
        new SortBy(toExpression("integer"), Direction.ASC).andThen(
            new SortBy(toExpression("decimal"), Direction.DESC)),
        expressionRealizer);
    input.sort(r.get());
    assertThat(input, contains(
        Tuple.of(tupleType),
        Tuple.of(tupleType, "integer", 1, "decimal", 4.0d),
        Tuple.of(tupleType, "integer", 1, "decimal", 3.0d),
        Tuple.of(tupleType, "integer", 1, "decimal", 2.0d)
    ));
  }

  @Test
  public void canCompareTuplesThatOnlyContainComparableItems() throws Exception {
    Struct parent = Struct.of("value", tupleType);
    List<Tuple> input = Lists.newArrayList(
        Tuple.ofValues(parent, Tuple.of(tupleType, "integer", 1, "decimal", 2.0d)),
        Tuple.ofValues(parent, Tuple.of(tupleType, "integer", 1, "decimal", 4.0d)),
        Tuple.ofValues(parent, Tuple.of(tupleType, "integer", 1, "decimal", 3.0d)));

    ResultOrProblems<Comparator<Tuple>> r = TupleComparator.createComparator(parent,
        new SortBy(toExpression("value"), Direction.ASC),
        expressionRealizer);

    input.sort(r.get());
    assertThat(input, contains(
        Tuple.ofValues(parent, Tuple.of(tupleType, "integer", 1, "decimal", 2.0d)),
        Tuple.ofValues(parent, Tuple.of(tupleType, "integer", 1, "decimal", 3.0d)),
        Tuple.ofValues(parent, Tuple.of(tupleType, "integer", 1, "decimal", 4.0d))

    ));
  }

  @Test
  public void errorIfAttributeNotKnown() throws Exception {
    Struct input = Struct.of("name", Types.TEXT);

    assertThat(
        TupleComparator.createComparator(
            input,
            new SortBy(toExpression("mane"), Direction.ASC),
            expressionRealizer),
        failedResult(
            equalTo(ExpressionProblems.get().noSuchStructMember("mane", Arrays.asList("name")))
        )
    );
  }

  @Test
  public void errorIfComparisionNotComparable() throws Exception {
    Struct input = Struct.of("name", Types.TEXT);

    assertThat(
        TupleComparator.createComparator(
            input,
            new SortBy(toExpression("[name]"), Direction.ASC),
            expressionRealizer),
        failedResult(isProblem(Severity.ERROR, ProblemCodes.EXPRESSION_RESULT_NOT_COMPARABLE)));
  }

  @Test
  public void errorIfTupleNotComparable() throws Exception {
    Struct child = Struct.of("a1", Types.TEXT, "a2", Struct.of("value", Types.TEXT));
    Struct parent = Struct.of("value", child);

    assertThat(
        TupleComparator.createComparator(
            parent,
            new SortBy(toExpression("value"), Direction.ASC),
            expressionRealizer),
        failedResult(isProblem(Severity.ERROR, ProblemCodes.EXPRESSION_RESULT_NOT_COMPARABLE)));
  }

  private Expression toExpression(String expr) {
    return expressionParser.parse(expr);
  }

}
