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

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

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.junit.Test;

import com.google.common.collect.ImmutableMap;

import nz.org.riskscape.engine.ProjectTest;
import nz.org.riskscape.engine.i18n.MutableMessageSource;
import nz.org.riskscape.engine.util.Pair;
import nz.org.riskscape.wizard.bld.IncrementalBuildState;
import nz.org.riskscape.wizard.bld.change.NoChange;
import nz.org.riskscape.wizard.survey2.BaseSurvey;

public class ConfigParserSurvey2WritingTest extends ProjectTest {

  Survey survey = new BaseSurvey("test", new MutableMessageSource(), s -> Collections.emptyList());

  IncrementalBuildState buildState = IncrementalBuildState.empty(
      new IncrementalBuildState.Context(survey, executionContext));

  EmptyQuestionSet questionSet = new EmptyQuestionSet("qs", survey);

  ConfigParser parser = new ConfigParser(id -> survey);

  Question q1 = addQuestion(new Question("q1", String.class));
  Question q2 = addQuestion(new Question("q2", Map.class));
  Question q3 = addQuestion(new Question("q3", Map.class).optionalMany());
  Question q4 = addQuestion(new Question("q4", Map.class));
  Question optional = addQuestion(new Question("optional", String.class).optionalOne());
  Question hidden = addQuestion(new Question("hidden", String.class).hidden());

  @Test
  public void canWriteOutASingleSimpleAnswer() {

    answer(q1, "simple");

    assertThat(
      getResponses(),
      contains(
        //Pair.of("survey", survey.getId()),
        Pair.of("version", parser.getVersion(buildState)),
        Pair.of("qs.q1", "simple")
      )
    );
  }

  @Test
  public void canWriteOutAMapAnswer() {

    answer(q2, ImmutableMap.of("foo", "1", "bar", "yay"));

    assertThat(
      getResponses(),
      contains(
        //Pair.of("survey", survey.getId()),
        Pair.of("version", parser.getVersion(buildState)),
        Pair.of("qs.q2[foo]", "1"),
        Pair.of("qs.q2[bar]", "yay")
      )
    );
  }

  @Test
  public void canWriteOutAManyMapAnswer() {
    answer(
      q3,
      ImmutableMap.of("foo", "1", "bar", "yay"),
      ImmutableMap.of("foo", "2", "bar", "yayo")
    );
    assertThat(
      getResponses(),
      contains(
        //Pair.of("survey", survey.getId()),
        Pair.of("version", parser.getVersion(buildState)),
        Pair.of("qs.q3[0][foo]", "1"),
        Pair.of("qs.q3[0][bar]", "yay"),
        Pair.of("qs.q3[1][foo]", "2"),
        Pair.of("qs.q3[1][bar]", "yayo")
      )
    );
  }

  @Test
  public void manyAnswersAreAlwaysSerializedWithAnArrayIndexEvenWhenOnlyOneIsRecorded() throws Exception {
    answer(
      q3,
      ImmutableMap.of("foo", "1", "bar", "yay")
    );

    assertThat(
      getResponses(),
      contains(
        //Pair.of("survey", survey.getId()),
        Pair.of("version", parser.getVersion(buildState)),
        Pair.of("qs.q3[0][foo]", "1"),
        Pair.of("qs.q3[0][bar]", "yay")
      )
    );
  }

  @Test
  public void aSkippedQuestionIsSkipped() {
    answer(optional);
    answer(
      q3,
      ImmutableMap.of("foo", "1", "bar", "yay")
    );

    assertThat(
      getResponses(),
      contains(
        //Pair.of("survey", survey.getId()),
        Pair.of("version", parser.getVersion(buildState)),
        Pair.of("qs.q3[0][foo]", "1"),
        Pair.of("qs.q3[0][bar]", "yay")
      )
    );
  }

  @Test
  public void aHiddenQuestionIsSkipped() {
    answer(hidden, Question.HIDDEN_VALUE);
    answer(q1, "simple");

    assertThat(
      getResponses(),
      contains(
        //Pair.of("survey", survey.getId()),
        Pair.of("version", parser.getVersion(buildState)),
        Pair.of("qs.q1", "simple")
      )
    );
  }


  @Test
  public void canWriteOutAMapWithListMembers() {
    answer(q4,
      ImmutableMap.of(
        "foo", Arrays.asList("foo-1", "foo-2"),
        "bar", "yay"
      )
    );

    assertThat(
      getResponses(),
      contains(
        //Pair.of("survey", survey.getId()),
        Pair.of("version", parser.getVersion(buildState)),
        Pair.of("qs.q4[foo][0]", "foo-1"),
        Pair.of("qs.q4[foo][1]", "foo-2"),
        Pair.of("qs.q4[bar]", "yay")
      )
    );
  }

  private Question addQuestion(Question question) {
    return question.inSet(questionSet);
  }

  private void answer(Question question, Object... unbound) {
    Answer answer = new Answer(
      question,
      Arrays.asList(unbound).stream().map(u -> new Answer.Response(u, u)).collect(Collectors.toList())
    );

    buildState =
        new NoChange(answer).make(buildState).get();
  }

  private List<Pair<String, String>> getResponses() {
    return parser.getConfigToWrite(buildState).collect(Collectors.toList());
  }

}
