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

import static org.junit.Assert.*;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.nio.file.Files;

import org.junit.Before;
import org.junit.Test;

import nz.org.riskscape.engine.Assert;

public class DefaultResourceFactoryTest {

  DefaultResourceFactory subject = new DefaultResourceFactory();
  File tempDir;
  byte[] bytes = new byte[] {1, 2, 3, 4};

  @Before
  public void setup() throws IOException {
    tempDir = Files.createTempDirectory("test").toFile();
  }

  @Test
  public void incrementCanRollFilesToAvoidClashes() throws Exception {
    File absoluteWithExtension = new File("/foo/bar/baz.txt");
    File rolled = subject.increment(absoluteWithExtension);
    assertEquals("/foo/bar/baz-1.txt", rolled.getPath());
    rolled = subject.increment(rolled);
    assertEquals("/foo/bar/baz-2.txt", rolled.getPath());

    File relativeWithExtension = new File("foo/bar/baz.txt");
    rolled = subject.increment(relativeWithExtension);
    assertEquals("foo/bar/baz-1.txt", rolled.getPath());
    rolled = subject.increment(rolled);
    assertEquals("foo/bar/baz-2.txt", rolled.getPath());

    File noPathAndExtension = new File("baz.txt");
    rolled = subject.increment(noPathAndExtension);
    assertEquals("baz-1.txt", rolled.getPath());
    rolled = subject.increment(rolled);
    assertEquals("baz-2.txt", rolled.getPath());

    File noPathAndNoExtension = new File("baz");
    rolled = subject.increment(noPathAndNoExtension);
    assertEquals("baz-1", rolled.getPath());
    rolled = subject.increment(rolled);
    assertEquals("baz-2", rolled.getPath());

    File pathWithIncrementEsque = new File("foo-1-is-cool-");
    rolled = subject.increment(pathWithIncrementEsque);
    assertEquals("foo-1-is-cool--1", rolled.getPath());
    rolled = subject.increment(rolled);
    assertEquals("foo-1-is-cool--2", rolled.getPath());

    // what kind of monster would do this?!
    File incrementInExtensionDoesNotCount = new File("foo.foo-1");
    rolled = subject.increment(incrementInExtensionDoesNotCount);
    assertEquals("foo-1.foo-1", rolled.getPath());
    rolled = subject.increment(rolled);
    assertEquals("foo-2.foo-1", rolled.getPath());

    // see how high this number can get
    File oddlyHighIncrementerIsFine = new File("foo-419.txt");
    rolled = subject.increment(oddlyHighIncrementerIsFine);
    assertEquals("foo-420.txt", rolled.getPath());
  }

  @Test
  public void createLetsUsCreateAFileInADirectory() throws Exception {
    CreateRequest request = new CreateRequest(tempDir.toURI(), "foo.txt", "text/plain");
    CreateHandle handle = subject.create(request);

    assertSame(request, handle.getRequest());

    URI writtenTo = handle.store(os -> os.write(bytes));

    File outputTo = new File(writtenTo.getPath());
    assertTrue(outputTo.exists());
    // meh, that'll do
    assertEquals(4, outputTo.length());
  }

  @Test
  public void createWillRollFilesIfThereAreAlreadyFilesInThatLocationWithTheSameName() throws Exception {
    CreateRequest request = new CreateRequest(new File(tempDir, "subdir").toURI(), "foo.txt", "text/plain");
    CreateHandle firstHandle = subject.create(request);

    URI writtenToFirst = firstHandle.store(os -> os.write(bytes));
    assertTrue(new File(writtenToFirst.getPath()).exists());

    CreateHandle secondHandle = subject.create(request);

    URI writtenToSecond = secondHandle.store(os -> os.write(bytes));
    assertTrue(new File(writtenToSecond.getPath()).exists());

    assertNotEquals(writtenToSecond, writtenToFirst);
    assertTrue(writtenToSecond.getPath().endsWith("foo-1.txt"));
  }

  @Test
  public void createWillReplaceFilesIfThereAreAlreadyFilesInThatLocationWithTheSameName() throws Exception {
    CreateRequest firstRequest = new CreateRequest(new File(tempDir, "subdir").toURI(), "foo.txt", "text/plain");
    CreateHandle firstHandle = subject.create(firstRequest);

    URI writtenToFirst = firstHandle.store(os -> os.write(bytes));
    assertTrue(new File(writtenToFirst.getPath()).exists());

    CreateRequest secondRequest = new CreateRequest(new File(tempDir, "subdir").toURI(), "foo.txt", "text/plain", true);
    CreateHandle secondHandle = subject.create(secondRequest);

    URI writtenToSecond = secondHandle.store(os -> os.write(bytes));
    assertTrue(new File(writtenToSecond.getPath()).exists());

    assertEquals(writtenToSecond, writtenToFirst);
    assertTrue(writtenToSecond.getPath().endsWith("foo.txt"));
  }

  @Test
  public void createWillCreateADirectoryIfItDoesNotAlreadyExist() throws Exception {
    CreateRequest request = new CreateRequest(new File(tempDir, "subdir").toURI(), "foo.txt", "text/plain");
    CreateHandle handle = subject.create(request);

    assertSame(request, handle.getRequest());

    URI writtenTo = handle.store(os -> os.write(bytes));

    File outputTo = new File(writtenTo.getPath());
    // check it was correctly nested
    assertEquals("subdir", outputTo.getParentFile().getName());
    assertEquals(tempDir, outputTo.getParentFile().getParentFile());

    // and it was written
    assertTrue(outputTo.exists());
    // meh, that'll do
    assertEquals(4, outputTo.length());

  }

  @Test
  public void createGivesANiceErrorIfUnrecognizedScheme() throws Exception {
    CreateException exception = Assert.assertThrows(CreateException.class, () ->
        subject.create(new CreateRequest(URI.create("http://google.com/riskscape"), "test-1.csv", "text/csv")));

    assertEquals(exception.getProblem(), ResourceProblems.get().unsupportedScheme("http"));
  }


  @Test
  public void createFailsIfContainerIsAFileNotADir() throws Exception {
    File inTheWay = new File(tempDir, "in the way.txt");
    inTheWay.createNewFile();
    CreateRequest request = new CreateRequest(inTheWay.toURI(), "foo.txt", "text/plain");
    CreateException exception = Assert.assertThrows(CreateException.class, () -> subject.create(request));
    assertEquals(exception.getProblem(), ResourceProblems.get().containerNotWritable(inTheWay.toURI()));
  }


  @Test
  public void createFailsIfContainerIsNotWriteable() throws Exception {
    tempDir.setWritable(false);
    CreateRequest request = new CreateRequest(tempDir.toURI(), "foo.txt", "text/plain");
    CreateException exception = Assert.assertThrows(CreateException.class, () -> subject.create(request));
    assertEquals(exception.getProblem(), ResourceProblems.get().containerNotWritable(tempDir.toURI()));
  }

  @Test
  public void createRemovesAHalfWrittenFileIfThereAreExceptions() throws Exception {
    CreateRequest request = new CreateRequest(tempDir.toURI(), "foo.txt", "text/plain");
    CreateHandle handle = subject.create(request);

    assertSame(request, handle.getRequest());

    Assert.assertThrows(CreateException.class, () -> handle.store(os -> {
      os.write(bytes);
      throw new IOException("good grief");
    }));

    assertEquals(0, tempDir.listFiles().length);
  }

}
