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

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

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

import org.junit.Test;

import nz.org.riskscape.engine.cli.ExitException;

public class RM286_Output_Order_By extends BaseModelRunCommandTest {

  List<List<String>> parsed;

  @Test
  public void canOrderByOnAttributeDefaultAscendingSort() throws Exception {
    parsed = runModel("sort",
        "report-event-impact.sort-by[0][attribute]=model",
        "report-event-impact.sort-by[0][direction]=ASC");
    assertThat(parsed, contains(
        makeCarLoss("VW", "Golf", 2014L, 15000L),
        makeCarLoss("VW", "Golf RS", 2018L, 60000L),
        makeCarLoss("Subaru", "Legacy", 1993L, 1000L),
        makeCarLoss("VW", "Polo", 2014L, 12000L)
    ));
  }

  @Test
  public void canOrderByTwoTextAttributes() throws Exception {
    parsed = runModel("sort",
        "report-event-impact.sort-by[0][attribute]=make",
        "report-event-impact.sort-by[0][direction]=ASC",
        "report-event-impact.sort-by[1][attribute]=model",
        "report-event-impact.sort-by[1][direction]=DESC");

    assertThat(parsed, contains(
        makeCarLoss("Subaru", "Legacy", 1993L, 1000L),
        makeCarLoss("VW", "Polo", 2014L, 12000L),
        makeCarLoss("VW", "Golf RS", 2018L, 60000L),
        makeCarLoss("VW", "Golf", 2014L, 15000L)
    ));
  }

  @Test
  public void canOrderByTextAndNumbericAttributes() throws Exception {
    parsed = runModel("sort",
        "report-event-impact.sort-by[0][attribute]=make",
        "report-event-impact.sort-by[0][direction]=ASC",
        "report-event-impact.sort-by[1][attribute]=value",
        "report-event-impact.sort-by[1][direction]=ASC");

    assertThat(parsed, contains(
        makeCarLoss("Subaru", "Legacy", 1993L, 1000L),
        makeCarLoss("VW", "Polo", 2014L, 12000L),
        makeCarLoss("VW", "Golf", 2014L, 15000L),
        makeCarLoss("VW", "Golf RS", 2018L, 60000L)
    ));
  }

  @Test
  public void canOrderByFunctions() throws Exception {
    parsed = runModel("sort-pipeline",
        "sortBy=[str_length(model), value]",
        "sortDirection=['DESC','ASC']"
    );

    assertThat(parsed, contains(
        makeCarLoss("VW", "Golf RS", 2018L, 60000L),
        makeCarLoss("Subaru", "Legacy", 1993L, 1000L),
        makeCarLoss("VW", "Polo", 2014L, 12000L),
        makeCarLoss("VW", "Golf", 2014L, 15000L)
    ));
  }

  @Test
  public void canOrderByLiterals_WhichDoNotOrder() throws Exception {
    //We aren't checking ordering here at all. Rather that expressions that evaluate to static values don't
    //kill the system.
    parsed = runModel("sort-pipeline",
        "sortBy='\\'statictext\\''");

    assertThat(parsed, containsInAnyOrder(
        makeCarLoss("VW", "Golf RS", 2018L, 60000L),
        makeCarLoss("Subaru", "Legacy", 1993L, 1000L),
        makeCarLoss("VW", "Polo", 2014L, 12000L),
        makeCarLoss("VW", "Golf", 2014L, 15000L)
    ));
  }

  @Test
  public void aBadOrderByGivesAHelpfulError() throws Exception {
    ExitException ex = assertThrows(ExitException.class,
        () -> runModel("sort-pipeline", "sortBy=unknown_function()"));

    assertThat(render(ex.getProblem()),
        containsString("Could not find function with id unknown_function")
    );
  }

  @Test
  public void aBadOrderByGivesAHelpfulError_UnknownAttribute() throws Exception {
    ExitException ex = assertThrows(ExitException.class,
        () -> runModel("sort-pipeline", "sortBy=engine_size"));

    assertThat(render(ex.getProblem()),
        containsString("- Could not find 'engine_size' among [make, model, year, value]")
    );
  }

  @Test
  public void canSortByTuples() throws Exception {
    // take a short-cut and use the splat operator that expands out to the whole tuple
    // (we could sort by the consequence struct, but we'd have to modify the select
    // and expected fieldnames as well)
    parsed = runModel("sort-pipeline", "sortBy=*");

    assertThat(parsed, containsInAnyOrder(
      makeCarLoss("Subaru", "Legacy", 1993L, 1000L),
      makeCarLoss("VW", "Golf", 2014L, 15000L),
      makeCarLoss("VW", "Golf RS", 2018L, 60000L),
      makeCarLoss("VW", "Polo", 2014L, 12000L)
    ));
  }

  private List<List<String>> runModel(String modelId, String... params) throws Exception {
    runCommand.modelId = modelId;
    runCommand.parameters = Arrays.asList(params);
    runCommand.run();

    return openCsv("event-impact.csv", "make", "model", "year", "value");
  }

  private List<String> makeCarLoss(String make, String model, Long year, Long value) {
    return Arrays.asList(make, model, year.toString(), value.toString());
  }
}
