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

import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;
import java.util.stream.LongStream;

import org.junit.Test;

import com.google.common.base.Strings;

import nz.org.riskscape.engine.types.Nullable;
import nz.org.riskscape.engine.types.Types;

public class SegmentedListTest {

  @Test
  public void segmentedListOfLongsTest() throws Exception {
    SegmentedList<Long> list = (SegmentedList<Long>) SegmentedList.forClass(Long.class);
    assertEquals(0, list.size());
    assertEquals(0, list.getNumSegments());
    assertFalse(list.iterator().hasNext());

    list.add(1L);
    assertEquals(1, list.size());
    assertThat(list, contains(1L));

    list.addAll(longs(2, 16));
    assertEquals(16, list.size());
    assertThat(list, equalTo(longs(1, 16)));
    assertEquals(1, list.getNumSegments());

    list.add(17L);
    assertEquals(17, list.size());
    assertEquals(2, list.getNumSegments());
    assertThat(list, equalTo(longs(1, 17)));

    list.addAll(longs(18, 100));
    assertEquals(100, list.size());
    assertEquals(3, list.getNumSegments());
    assertThat(list, equalTo(longs(1, 100)));
  }

  @Test
  public void segmentedListOfNullalbeIntegerTest() throws Exception {
    SegmentedList<Object> list = (SegmentedList<Object>) SegmentedList.forType(Nullable.INTEGER);
    assertEquals(0, list.size());
    assertEquals(0, list.getNumSegments());
    assertFalse(list.iterator().hasNext());

    list.add(1L);
    list.add(null);
    list.add(null);
    list.add(10L);
    assertThat(list, contains(is(1L), nullValue(), nullValue(), is(10L)));
  }

  @Test
  public void segmentedListOfDoublesTest() throws Exception {
    SegmentedList<Double> list = (SegmentedList<Double>) SegmentedList.forClass(Double.class);
    assertEquals(0, list.size());
    assertEquals(0, list.getNumSegments());
    assertFalse(list.iterator().hasNext());

    list.add(1D);
    assertEquals(1, list.size());
    assertThat(list, contains(1D));

    list.addAll(doubles(2, 16));
    assertEquals(16, list.size());
    assertThat(list, equalTo(doubles(1, 16)));
    assertEquals(1, list.getNumSegments());

    list.add(17D);
    assertEquals(17, list.size());
    assertEquals(2, list.getNumSegments());
    assertThat(list, equalTo(doubles(1, 17)));

    list.addAll(doubles(18, 100));
    assertEquals(100, list.size());
    assertEquals(3, list.getNumSegments());
    assertThat(list, equalTo(doubles(1, 100)));
  }

  @Test
  public void segmentedListOfFloatsTest() throws Exception {
    List<Float> list = SegmentedList.forType(Types.SMALLFLOAT);
    assertEquals(0, list.size());
    assertFalse(list.iterator().hasNext());

    list.add(1F);
    assertEquals(1, list.size());
    assertThat(list, contains(1F));

    list.addAll(floats(2, 16));
    assertEquals(16, list.size());
    assertThat(list, equalTo(floats(1, 16)));

    list.add(17F);
    assertEquals(17, list.size());
    assertThat(list, equalTo(floats(1, 17)));

    list.addAll(floats(18, 100));
    assertEquals(100, list.size());
    assertThat(list, equalTo(floats(1, 100)));
  }

  @Test
  public void segmentedListOfNullalbeFloatingTest() throws Exception {
    SegmentedList<Object> list = (SegmentedList<Object>) SegmentedList.forType(Nullable.FLOATING);
    assertEquals(0, list.size());
    assertEquals(0, list.getNumSegments());
    assertFalse(list.iterator().hasNext());

    list.add(1.5D);
    list.add(null);
    list.add(null);
    list.add(10.5D);
    assertThat(list, contains(is(1.5D), nullValue(), nullValue(), is(10.5D)));
  }

  @Test
  public void segmentedListOfObjectsTest() throws Exception {
    SegmentedList<String> list = (SegmentedList<String>) SegmentedList.forClass(String.class);
    assertEquals(0, list.size());
    assertEquals(0, list.getNumSegments());
    assertFalse(list.iterator().hasNext());

    list.add("1");
    assertEquals(1, list.size());
    assertThat(list, contains("1"));

    list.addAll(strings(2, 16));
    assertEquals(16, list.size());
    assertThat(list, equalTo(strings(1, 16)));
    assertEquals(1, list.getNumSegments());

    list.add("17");
    assertEquals(17, list.size());
    assertEquals(2, list.getNumSegments());
    assertThat(list, equalTo(strings(1, 17)));

    list.addAll(strings(18, 100));
    assertEquals(100, list.size());
    assertEquals(3, list.getNumSegments());
    assertThat(list, equalTo(strings(1, 100)));
  }

  @Test
  public void testAddAllAndSort() throws Exception {
    SegmentedList<Long> listA = (SegmentedList<Long>) SegmentedList.forClass(Long.class);
    listA.addAll(longs(1, 15));
    assertEquals(1, listA.getNumSegments());

    SegmentedList<Long> listB = (SegmentedList<Long>) SegmentedList.forClass(Long.class);
    listB.add(16L);
    listA.addAll(listB);
    // should have just copied the single trailing element in to the last segment
    assertEquals(2, listA.getNumSegments());
    assertThat(listA, equalTo(longs(1, 16)));
    // src list hasn't changed
    assertEquals(1, listB.getNumSegments());
    assertThat(listB, equalTo(longs(16, 16)));

    // make changes to both lists, check they work fine
    listA.add(17L);
    listB.add(15L);

    // additions post-add-all will always require a new segment
    assertEquals(3, listA.getNumSegments());
    assertEquals(2, listB.getNumSegments());
    assertThat(listB, contains(16L, 15L));
    assertThat(listA, equalTo(longs(1, 17)));

    // add list b in again
    listA.addAll(listB);
    assertEquals(5, listA.getNumSegments());
    List<Long> expected = longs(1, 17);
    expected.add(16L);
    expected.add(15L);
    assertThat(listA, equalTo(expected));

    // now do a more realistic test - fold a bunch of lists together
    List<List<Long>> toFold = Arrays.asList(
        SegmentedList.forClass(Long.class),
        SegmentedList.forClass(Long.class),
        SegmentedList.forClass(Long.class),
        SegmentedList.forClass(Long.class),
        SegmentedList.forClass(Long.class)
    );
    Random random = new Random();
    LongStream.range(0, 10000).forEach(aLong -> {
      int pickList = random.nextInt(toFold.size());
      toFold.get(pickList).add(aLong);
    });

    SegmentedList<Long> combined = toFold.stream()
        .map(list -> SegmentedList.class.cast(list))
        .reduce((lhs, rhs) -> lhs.fold(rhs)).get();
    assertThat(combined, hasSize(10000));
    combined.sort(Long::compareTo);
    // copy to array list to avoid awful random access performance
    assertThat(new ArrayList<>(combined), equalTo(longs(0, 9999)));
  }

  @Test
  public void testSortingLongs() throws Exception {
    List<Long> longs = longs(0, 10000);
    Collections.shuffle(longs);
    List<Long> segmentedLongs = SegmentedList.forClass(Long.class);
    segmentedLongs.addAll(longs);
    segmentedLongs.sort(Long::compareTo);

    assertThat(segmentedLongs, equalTo(longs(0, 10000)));
  }

  @Test
  public void testSortingDoubles() throws Exception {
    List<Double> doubles = doubles(0, 10000);
    Collections.shuffle(doubles);
    List<Double> segmentedDoubles = SegmentedList.forClass(Double.class);
    segmentedDoubles.addAll(doubles);
    segmentedDoubles.sort(Double::compareTo);

    assertThat(segmentedDoubles, equalTo(doubles(0, 10000)));
  }

  @Test
  public void testSortingFloats() throws Exception {
    List<Float> doubles = floats(0, 10000);
    Collections.shuffle(doubles);
    List<Float> segmentedDoubles = SegmentedList.forClass(Float.class);
    segmentedDoubles.addAll(doubles);
    segmentedDoubles.sort(Float::compareTo);

    assertThat(segmentedDoubles, equalTo(floats(0, 10000)));
  }

  @Test
  public void testSortingStrings() throws Exception {
    List<String> strings = strings(0, 10000);
    Collections.shuffle(strings);
    List<String> segmentedStrings = SegmentedList.forClass(String.class);
    segmentedStrings.addAll(strings);
    segmentedStrings.sort(String::compareTo);

    strings.sort(String::compareTo);

    assertThat(segmentedStrings, equalTo(strings));
  }

  public List<Long> longs(int start, int stop) {
    return LongStream.range(start, stop + 1).mapToObj(Long::valueOf).collect(Collectors.toList());
  }

  public List<Double> doubles(int start, int stop) {
    return LongStream.range(start, stop + 1).mapToObj(Double::valueOf).collect(Collectors.toList());
  }

  public List<Float> floats(int start, int stop) {
    return LongStream.range(start, stop + 1).mapToObj(Float::valueOf).collect(Collectors.toList());
  }

  // return unpadded strings
  public List<String> strings(int start, int stop) {
    return strings(start, stop, 0);
  }

  // padTo is the biggest number we expect to have ever in the test cases. and pad to this size so that sorting works
  public List<String> strings(int start, int stop, int padTo) {
    int padLength = Long.toString(padTo).length();
    return LongStream.range(start, stop + 1).mapToObj(aLong -> Strings.padStart(Long.toString(aLong), padLength, '0'))
        .collect(Collectors.toList());
  }

}
