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

import static nz.org.riskscape.engine.Matchers.*;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;

import java.util.ArrayList;
import java.util.List;

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

import nz.org.riskscape.engine.Tuple;
import nz.org.riskscape.engine.rl.BaseExpressionRealizerTest;
import nz.org.riskscape.engine.rl.DefaultOperators;
import nz.org.riskscape.engine.rl.LanguageFunctions;
import nz.org.riskscape.engine.types.Nullable;
import nz.org.riskscape.engine.types.RSList;
import nz.org.riskscape.engine.types.Struct;
import nz.org.riskscape.engine.types.Types;

@SuppressWarnings("unchecked")
public class ListSortTest extends BaseExpressionRealizerTest {

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

  @Test
  public void willSortIntegers() {
    assertThat((List<Long>) evaluateConstant("sort([8, 3, 77, 2])"), contains(
        2L, 3L, 8L, 77L
    ));
    assertThat(realized.getResultType(), is(RSList.create(Types.INTEGER)));
  }

  @Test
  public void willSortIntegersInReverseOrder() {
    assertThat((List<Long>) evaluateConstant("sort([8, 3, 77, 2], options: {direction: 'DESC'})"),
        contains(
            77L, 8L, 3L, 2L
        )
    );
    assertThat(realized.getResultType(), is(RSList.create(Types.INTEGER)));
  }

  @Test
  public void doesNotAlterInputList() {
    List<Long> items = List.of(8L, 2L);
    Struct inputType = Struct.of("items", RSList.create(Types.INTEGER));
    assertThat((List<Long>) evaluate("sort(items)", Tuple.ofValues(inputType, items)), allOf(
        not(sameInstance(items)),
        contains(
            2L, 8L
        )
    ));
    // and it hasn't changed either
    assertThat(items, contains(8L, 2L));
  }

  @Test
  public void willSortFloating() {
    assertThat((List<Double>) evaluateConstant("sort([1.6, 1.3, 1.89, 1.2])"), contains(
        1.2D, 1.3D, 1.6D, 1.89D
    ));
    assertThat(realized.getResultType(), is(RSList.create(Types.FLOATING)));
  }

  @Test
  public void willSortText() {
    assertThat((List<String>) evaluateConstant("sort(['zoo', 'doo', 'Party', 'time'])"), contains(
        // upper case comes first
        "Party", "doo", "time", "zoo"
    ));
    assertThat(realized.getResultType(), is(RSList.create(Types.TEXT)));
  }

  @Test
  public void willSortWithNullableItems() {
    assertThat((List<String>) evaluateConstant("sort(['zoo', null, 'doo', 'Party', 'time'])"),
        contains(
            is("Party"), is("doo"), is("time"), is("zoo"), nullValue()
        )
    );
    assertThat(realized.getResultType(), is(RSList.create(Nullable.TEXT)));
  }

  @Test
  public void willNotSortTuplesWithoutCustomBy() {
    Struct itemType = Struct.of("name", Types.TEXT, "value", Types.INTEGER);
    Struct inputType = Struct.of("items", RSList.create(itemType));
    evaluate("sort(items)", Tuple.of(inputType, "items", List.of(Tuple.ofValues(itemType, "car", 10000L))));

    assertThat(realizationProblems, contains(hasAncestorProblem(
        is(ListSort.PROBLEMS.listItemsNotComparable(itemType, ListSort.PROBLEMS.listItemsNotComparableHint()))
    )));
  }

  @Test
  public void willSortTupleUsingByLambda() {
    assertThat((List<Tuple>) evaluateConstant("sort([{foo: 'foo'}, {foo: 'bar'}], by: (i) -> i.foo)"),
        contains(
            tuple("{foo: 'bar'}"),
            tuple("{foo: 'foo'}")
        ));
  }

  @Test
  public void willSortTupleWithNullBySortBy() {
    Struct expectedItemType = Struct.of("foo", Nullable.TEXT);
    assertThat((List<Tuple>) evaluateConstant("sort([{foo: null}, {foo: 'bar'}], by: (i) -> i.foo)"),
        is(
            tuples(expectedItemType, "['bar']", "[null_of('text')]")
        )
    );
  }

  @Test
  public void willSortTupleWithNullItem() {
    Struct itemType = Struct.of("foo", Types.TEXT);
    Struct inputType = Struct.of("items", RSList.create(Nullable.of(itemType)));
    List<Tuple> items = new ArrayList<>();
    items.add(tuple("{foo: 'zzz'}"));
    items.add(null);
    items.add(tuple("{foo: 'abc'}"));

    assertThat((List<Tuple>) evaluate("sort(items, by: (i) -> i.foo)", Tuple.ofValues(inputType, items)),
        contains(
            is(tuple("{foo: 'abc'}")),
            is(tuple("{foo: 'zzz'}")),
            nullValue()
        )
    );
  }

  @Test
  public void willSortTupleWithNullItemInReverseOrder() {
    Struct itemType = Struct.of("foo", Types.TEXT);
    Struct inputType = Struct.of("items", RSList.create(Nullable.of(itemType)));
    List<Tuple> items = new ArrayList<>();
    items.add(tuple("{foo: 'zzz'}"));
    items.add(null);
    items.add(tuple("{foo: 'abc'}"));

    assertThat((List<Tuple>) evaluate("sort(items, by: (i) -> i.foo, options: {direction: 'DESC'})",
            Tuple.ofValues(inputType, items)
        ),
        contains(
            is(tuple("{foo: 'zzz'}")),
            is(tuple("{foo: 'abc'}")),
            nullValue()
        )
    );
  }

  @Test
  public void canMapUsingOuterScope() {
    Struct inputType = Struct.of(
        "value", Types.INTEGER,
        "items", RSList.create(Types.INTEGER)
    );
    assertThat((List<Long>) evaluate("sort(items, (i) -> value - i)",
        Tuple.ofValues(inputType, 100L, List.of(100L, 50L, 1L, 99L))), contains(
            100L, 99L, 50L, 1L
        )
    );
  }

  @Test
  public void canMapUsingOuterScopeLambdaReplacesAttribute() {
    Struct inputType = Struct.of(
        // an attribute that should get replaced by the list member in the lambda scope
        "i", Types.INTEGER,
        "value", Types.INTEGER,
        "items", RSList.create(Types.INTEGER)
    );
    assertThat((List<Long>) evaluate("sort(items, (i) -> value - i)",
        Tuple.ofValues(inputType, -100L, 100L, List.of(100L, 50L, 1L, 99L))), contains(
            100L, 99L, 50L, 1L
        )
    );
  }

}
