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

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

import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Consumer;

import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;

import com.google.common.collect.ImmutableMap;

import nz.org.riskscape.engine.Engine;
import nz.org.riskscape.engine.Matchers;
import nz.org.riskscape.engine.bind.BindingContext;
import nz.org.riskscape.engine.bind.ParamProblems;
import nz.org.riskscape.engine.bind.Parameter;
import nz.org.riskscape.engine.bind.ParameterField;
import nz.org.riskscape.engine.bind.ParameterSet;
import nz.org.riskscape.engine.pipeline.ExecutionContext;
import nz.org.riskscape.engine.problem.GeneralProblems;
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 BaseBookmarkResolverParameterBindingTest {

  public static class TestParameters extends BookmarkParameters {
    @ParameterField
    boolean flag = false;

    @ParameterField
    Double width;

    @ParameterField
    int height = 100;

    @ParameterField
    Optional<String> string = Optional.empty();

    @SuppressWarnings("rawtypes")
    @ParameterField
    Map attrMap = Collections.EMPTY_MAP;

    @ParameterField(minRequired = 0)
    public List<Integer> integers = new ArrayList<>();

    @Override
    public Class<?> getDataType() {
      return Object.class;
    }
  }

  Consumer<TestParameters> validator;

  class Subject extends BaseBookmarkResolver<TestParameters> {

    Subject(Engine engine) {
      super(engine);
    }

    @Override
    protected Map<String, String> getExtensionsToFormats() {
      return Collections.emptyMap();
    }

    @Override
    protected void validateParameters(TestParameters testParams, BindingContext localBindingContext) {

      if (validator != null) {
        validator.accept(testParams);
      }
    }

    @Override
    protected ResultOrProblems<Object> build(TestParameters testParams) {
      return null;
    }

  }

  ExecutionContext executionContext = Mockito.mock(ExecutionContext.class);
  BindingContext bindingContext = Mockito.mock(BindingContext.class);
  Engine engine = Mockito.mock(Engine.class);
  Subject subject = new Subject(engine);
  Map<String, Object> params = new HashMap<>();
  Bookmark.BookmarkBuilder bookmarkBuilder = Bookmark.builder()
      .id("foo")
      .location(URI.create("http://riskscape.com"));

  TestParameters testParameters;
  List<Problem> validationProblems;

  @Before
  public void setup() {
    Mockito.when(executionContext.getBindingContext()).thenReturn(bindingContext);
    Mockito.when(bindingContext.bind(Mockito.any(), Mockito.any(Parameter.class)))
      .thenAnswer(a -> ResultOrProblems.of(a.getArgument(0)));
  }


  @Test
  public void checkBasicBindingFunctionalityWorks() throws Exception {
    params.put("flag", true);
    params.put("height", 1);
    params.put("width", 4.0D);
    params.put("string", "cool");
    params.put("integers", Arrays.asList(1, 2, 3));

    validate();

    assertThat(validationProblems, empty());

    assertEquals(testParameters.flag, true);
    assertEquals(testParameters.height, 1);
    assertEquals(testParameters.width.doubleValue(), 4.0D, 0.00001);
    assertEquals(testParameters.string.get(), "cool");
    assertEquals(testParameters.integers, Arrays.asList(1, 2, 3));
  }

  @Test
  public void requiredParametersProduceValidationErrorsIfMissing() throws Exception {
    validate();

    assertThat(validationProblems, not(empty()));

    assertThat(validationProblems, contains(
      GeneralProblems.get().required(subject.getParameterSet().get("width"))
    ));
  }

  @Test
  public void bindingErrorsAreReturnedAsValidationErrors() throws Exception {
    Mockito.when(bindingContext.bind(Mockito.any(Object.class), Mockito.any(Parameter.class)))
      .thenReturn(ResultOrProblems.failed(Problems.foundWith("you")));

    params.put("width", 4.0D);
    params.put("height", "cool");

    validate();

    assertThat(validationProblems, containsInAnyOrder(
      Problems.foundWith("you")
    ));
  }

  @Test
  public void subClassesCanPerformExtraValidationOnTheBoundParametersObject() throws Exception {
    params.put("string", "cool");

    Problem probs = Problem.warning("story");
    this.validator = (testParams) -> {
      assertEquals(testParams.string.get(), "cool");
      testParams.add(probs);
    };

    validate();

    assertThat(validationProblems, hasItem(probs));
  }

  @Test
  public void unrecogizedParametersProduceAWarning() throws Exception {
    params.put("junk", "rad");

    validate();

    assertThat(validationProblems, hasItem(
        Matchers.isProblem(Severity.WARNING, containsString("Unrecognized parameters given - [junk]"))
    ));
  }

  @Test
  public void parametersWithDotsAreTransformedInToMaps() throws Exception {
    params.put("attrMap.foo", "story");
    params.put("attrMap.bar", "cool");

    validate();

    testParameters.attrMap = ImmutableMap.of("foo", "story", "bar", "cool");
  }

  @Test
  public void surplusNestedParameterProduceAnError() throws Exception {
    params.put("attrMap.foo", Arrays.asList("rad", "cool"));

    validate();

    assertThat(validationProblems, hasItem(
        ParamProblems.get().wrongNumberGiven("attrMap.foo", "1", 2)
    ));
  }

  @Test
  public void checkBadBindingArityProducesError() throws Exception {
    params.put("height", 1);
    params.put("width", Arrays.asList(4.0D, 20.0D));

    validate();

    assertThat(validationProblems, contains(
        is(ParamProblems.get().wrongNumberGiven("width", "1", 2))
    ));
  }

  private void validate() {
    Bookmark bookmark = bookmarkBuilder.build().addUnparsed(ParameterSet.normaliseParameterMap(params));
    testParameters = subject.bindAndValidate(bookmark, executionContext);

    validationProblems = testParameters.problems;
  }


}
