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

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

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

import org.junit.Test;

import lombok.Getter;
import lombok.RequiredArgsConstructor;
import nz.org.riskscape.engine.problem.GeneralProblems;
import nz.org.riskscape.engine.resource.Resource;
import nz.org.riskscape.engine.util.Pair;
import nz.org.riskscape.problem.Problem;
import nz.org.riskscape.problem.Problem.Severity;
import nz.org.riskscape.problem.Problems;
import nz.org.riskscape.problem.ResultOrProblems;

public class IdentifiedCollectionTest {

  @RequiredArgsConstructor
  public static class TestIdentified implements Identified {
    @Getter
    private final String id;
  }
  IdentifiedCollection.Base<TestIdentified> subject =
      new IdentifiedCollection.Base<TestIdentified>(TestIdentified.class);

  TestIdentified t1 = new TestIdentified("t1");
  TestIdentified t2 = new TestIdentified("t2");

  Problem badValue = GeneralProblems.get().badValue("foo", TestIdentified.class, "more foo-like");

  @Test
  public void canAddAndGetASinglePreBuiltThing() throws Exception {
    subject.add(t1);
    assertSame(t1, subject.get("t1"));
  }

  @Test
  public void canAddAndGetASingleDelayedBuiltThing() throws Exception {
    subject.add("t1", Resource.UNKNOWN, () -> ResultOrProblems.of(t1));
    assertSame(t1, subject.get("t1"));
  }

  @Test
  public void getWillLogAnyProblemsToGivenSink() throws Exception {
    List<Problem> collected  = new ArrayList<>();
    Problem fooProblem = Problems.foundWith("foo").withSeverity(Severity.WARNING);
    subject.add("t1", Resource.UNKNOWN, () -> ResultOrProblems.of(t1, fooProblem));
    assertSame(t1, subject.get("t1", p -> collected.add(p)));

    assertEquals(collected, Arrays.asList(fooProblem));
  }

  @Test
  public void addThrowsAnExceptionIfPreviouslyBuiltThingAlreadyExistsWithThatId() throws Exception {
    subject.add(t1);
    try {
      subject.add(t1);
      fail("should have thrown");
    } catch (ObjectAlreadyExistsException ex) {
      assertSame(t1, ex.getExisting());
    }
  }

  @Test
  public void addThrowsAnExceptionIfPreviouslyBuiltFailedThingAlreadyExistsWithThatId() throws Exception {
    subject.add("t1", Resource.UNKNOWN, () -> ResultOrProblems.failed(badValue));
    try {
      subject.add(t1);
      fail("should have thrown");
    } catch (ObjectAlreadyExistsException ex) {
      assertNotSame(t1, ex.getExisting());
      assertSame(TestIdentified.class, ex.getExisting().getIdentifiedClass());
    }
  }

  @Test
  public void aFailedThingThrowsAnErrorOnGet() throws Exception {
    subject.add("t1", Resource.UNKNOWN, () -> ResultOrProblems.failed(badValue));
    try {
      subject.get("t1");
      fail("should have thrown");
    } catch (FailedObjectException ex) {
      assertEquals("t1", ex.getId());
      assertEquals(badValue, ex.getProblem().getChildren().get(0));
    }
  }

  @Test
  public void aMissingThingThrowsAnErrorOnGet() throws Exception {
    try {
      subject.get("t1");
      fail("should have thrown");
    } catch (NoSuchObjectException ex) {

    }
  }

  @Test
  public void getResultReturnsAFailedThingWithItsFailures() throws Exception {
    ResultOrProblems<TestIdentified> built = ResultOrProblems.failed(badValue);
    subject.add("t1", Resource.UNKNOWN, () -> built);

    assertSame(built, subject.getResult("t1").get());
  }


  @Test()
  public void getResultReturnsEmptyIfNoObjectExists() throws Exception {
    assertFalse(subject.getResult("foo").isPresent());
  }


  @Test
  public void getAllReturnsAllSuccessfullyBuiltThings() throws Exception {
    ResultOrProblems<TestIdentified> built = ResultOrProblems.failed(badValue);
    subject.add(t1);
    subject.add(t2);
    subject.add("foo", Resource.UNKNOWN, () -> built);

    assertEquals(Arrays.asList(t1, t2), subject.getAll());
  }

  @Test
  public void validateAllReturnsAListOfAllFailures() throws Exception {
    ResultOrProblems<TestIdentified> built = ResultOrProblems.failed(badValue);
    subject.add(t1);
    subject.add(t2);
    subject.add("foo", Resource.UNKNOWN, () -> built);

    assertEquals(Arrays.asList(Pair.of("foo", built.getProblems())), subject.getAllProblems());
  }

  @Test
  public void testGetSimilarIds() {
    subject.add(new TestIdentified("abcd"));
    subject.add(new TestIdentified("bcde"));
    subject.add(new TestIdentified("defg"));

    // first lets check then there are not enough characters
    assertThat(subject.getSimilarIds(""), hasSize(0));
    assertThat(subject.getSimilarIds("a"), hasSize(0));

    assertThat(subject.getSimilarIds("ab"), containsInAnyOrder("abcd"));
    assertThat(subject.getSimilarIds("bc"), containsInAnyOrder("abcd", "bcde"));
    assertThat(subject.getSimilarIds("ef"), containsInAnyOrder("defg"));
    assertThat(subject.getSimilarIds("exyz"), hasSize(0));
  }

}
