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

import static org.junit.Assert.*;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Comparator;
import java.util.List;

import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;
import org.junit.After;
import org.junit.Before;

import nz.org.riskscape.engine.CapturingStream;
import nz.org.riskscape.engine.i18n.DefaultMessages;
import nz.org.riskscape.engine.i18n.ResourceClassLoader;
import nz.org.riskscape.engine.plugin.ExtensionPoints;
import nz.org.riskscape.problem.Problem;
import nz.org.riskscape.test.TestUtils;

/**
 * Helper class containing base command test utilities and set up code.  Can be extended by test classes or used as
 * utility code from another.
 */
public class TerminalTestHelper {

  public CapturingStream outStream = new CapturingStream();
  public CapturingStream errorStream = new CapturingStream();
  public SwitchableByteArrayInputStream inputStream = new SwitchableByteArrayInputStream("".getBytes());

  public Path tempDir;
  // TODO consider implementing EngineTest (or a sub interface) and get messages from that instead of building our own.
  public DefaultMessages messages = new DefaultMessages(new ExtensionPoints());
  // most recently created terminal
  public TestTerminal terminal = createTerminal();

  public String render(Problem problem) {
    return messages.renderProblem(problem).toString();
  }

  @Before
  public void setupTerminalCapture() throws Exception {
    //Create a temp dir for model to write to.
    tempDir = Files.createTempDirectory("model-tests");
  }

  @Before
  public void loadI18n() throws MalformedURLException {
    URL i18nUrl = TestUtils.getRootProjectPath().get()
        .resolve(Paths.get("engine", "core", "src", "main", "i18n")).toUri().toURL();

    ResourceClassLoader loader = new ResourceClassLoader("", i18nUrl);
    messages.getClassLoader().append(this, loader);
  }

  @After
  public void breakDownTerminalCapture() throws Exception {
    if (!Files.exists(tempDir)) {
      return;
    }

    Files.walk(tempDir)
        .sorted(Comparator.reverseOrder())
        .map(Path::toFile)
        .forEach(File::delete);

    if (outStream != null) {
      outStream.close();
      outStream = null;
    }
    if (errorStream != null) {
      errorStream.close();
      errorStream = null;
    }
  }

  protected <T extends TerminalCommand> T addCommandDependencies(T command) {
    command.setTerminal(createTerminal());
    command.setMessages(messages);
    return command;
  }

  public TestTerminal createTerminal() {
    this.terminal = new TestTerminal(errorStream.getPrintStream(), outStream.getPrintStream(), inputStream,
        messages);
    return terminal;
  }

  /**
   * Asserts that file exists beneath tempDir.
   *
   * @param pathElement to file
   */
  protected void assertFileExists(String... pathElement) {
    Path target = tempDir;
    for (String p : pathElement) {
      target = target.resolve(p);
    }

    assertTrue(String.format("File '%s' does not exist", target.toString()), target.toFile().exists());
  }

  public static Matcher<Table> table(
      Matcher<? super List<String>> headerMatcher,
      Matcher<? super List<List<String>>> rowMatcher) {
    return new TypeSafeMatcher<Table>(Table.class) {

      @Override
      public void describeTo(Description description) {
        description.appendText("Header ")
            .appendDescriptionOf(headerMatcher)
            .appendText(" Row ")
            .appendDescriptionOf(rowMatcher);
      }

      @Override
      protected void describeMismatchSafely(Table table, Description description) {
        if (!headerMatcher.matches(table.getHeader())) {
          description.appendText("mismatched header").appendValue(table.getHeader());
        }
        if (!rowMatcher.matches(table.getRows())) {
          description.appendText("mismatched rows").appendValue(table.getRows());
        }
      }

      @Override
      protected boolean matchesSafely(Table table) {
        return headerMatcher.matches(table.getHeader()) && rowMatcher.matches(table.getRows());
      }
    };
  }

}
