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

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

import java.net.URI;

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

import nz.org.riskscape.engine.FileProblems;
import nz.org.riskscape.engine.bind.BindingContext;
import nz.org.riskscape.engine.bind.Parameter;

public class UriBinderTest {

  UriBinder subject = new UriBinder();
  Parameter parameter = Parameter.optional("foo", URI.class);
  BindingContext context = mock(BindingContext.class);

  @Before
  public void setup() {
    // relative to a project - the dirname is used to resolve the paths
    when(context.getRelativeTo()).thenReturn(URI.create("file:///root/project.ini"));
  }

  @Test
  public void aPassableLookingUriBindsToAUri() {
    URI httpUri = (URI) subject.bind(context, parameter, "http://google.com/foo.html");
    assertEquals("http", httpUri.getScheme());
    assertEquals("google.com", httpUri.getAuthority());
    assertEquals("/foo.html", httpUri.getPath());

    URI fileUri = (URI) subject.bind(context, parameter, "file:///foo/bar/baz");
    assertEquals("file", fileUri.getScheme());
    assertNull(fileUri.getAuthority());
    assertEquals("/foo/bar/baz", fileUri.getPath());
  }

  @Test
  public void aPassableLookingUriBindsToAUriWithSchemeLessContext() {
    // URI schemes can be null so the binder needs to cope with this. This could be more likely to
    // occur from tests in practice though because of how the project normally constructs the relative
    // to path
    when(context.getRelativeTo()).thenReturn(URI.create("project.ini"));
    assertNull(context.getRelativeTo().getScheme());

    URI httpUri = (URI) subject.bind(context, parameter, "http://google.com/foo.html");
    assertEquals("http", httpUri.getScheme());
    assertEquals("google.com", httpUri.getAuthority());
    assertEquals("/foo.html", httpUri.getPath());

    URI fileUri = (URI) subject.bind(context, parameter, "file:///foo/bar/baz");
    assertEquals("file", fileUri.getScheme());
    assertNull(fileUri.getAuthority());
    assertEquals("/foo/bar/baz", fileUri.getPath());
  }

  @Test
  public void aSchemeLessUriIsConvertedToAFileRelativeToProjectBase() throws Exception {
    assertEquals(URI.create("file:///root/foo"), subject.bind(context, parameter, "foo"));
    assertEquals(URI.create("file:///root/foo/bar"), subject.bind(context, parameter, "foo/bar"));
    assertEquals(URI.create("file:///root/foo/bar.txt"), subject.bind(context, parameter, "foo/bar.txt"));

    when(context.getRelativeTo()).thenReturn(URI.create("custom-protocol://backend/path/to/project/"));
    assertEquals(URI.create("custom-protocol://backend/path/to/project/foo"), subject.bind(context, parameter, "foo"));
  }

  @Test
  public void aRelativeWindowsPathIsConvertedToAFileRelativeToProjectBase() throws Exception {
    // this one is a dir, not a project - it makes no difference to the result
    when(context.getRelativeTo()).thenReturn(URI.create("file:///c:/root/"));

    // note the backslashes in the path
    assertEquals(URI.create("file:///c:/root/foo/bar"), subject.bind(context, parameter, "foo\\bar"));
  }

  @Test
  public void aSchemeLessUriWithAnAbsolutePathIsConvertedToAnAbsoluteFile() throws Exception {
    assertEquals(URI.create("file:///foo/bar"), subject.bind(context, parameter, "/foo/bar"));
  }

  @Test
  public void aSchemeLessWindowsPathWithADriveSpecifierIsConvertedToAnAbsoluteFile() throws Exception {
    // prove this behaviour is nothing to do with the project base (at least for now)
    // in the future, we might decide that file proto is only allowed for file projects, to avoid hackers haxxing us
    when(context.getRelativeTo()).thenReturn(URI.create("http://riskscape.com"));

    assertEquals(URI.create("file:///s:/baz/foo/test.com"), subject.bind(context, parameter, "s:\\baz\\foo\\test.com"));

    // this is actually a valid uri in itself, so we can't really convert it, plus what windows user is going to use
    // forward slashes in a path?
    URI uri = (URI) subject.bind(context, parameter, "c:/foo/bar");
    assertEquals("c", uri.getScheme());
    assertEquals("/foo/bar", uri.getSchemeSpecificPart());
  }

  @Test
  public void encodesSpaceCharacters() throws Exception {
    assertEquals(URI.create("file:///foo/bar%20baz"), subject.bind(context, parameter, "/foo/bar baz"));

    when(context.getRelativeTo()).thenReturn(URI.create("file:///c:/root/"));
    assertEquals(URI.create("file:///c:/root/foo/bar%20baz"), subject.bind(context, parameter, "foo\\bar baz"));
  }

  @Test
  public void backlashesInNonFileProjectsPathsAreNotOK() throws Exception {
    when(context.getRelativeTo()).thenReturn(URI.create("http://foo.bar/cool"));

    assertThat(
      subject.bindValue(context, "\\foo\\bar", URI.class),
      failedResult(equalTo(FileProblems.get().backslashesNotAllowedInUris("\\foo\\bar")))
    );
  }

  @Test
  public void anInvalidUriThrowsAParameterException() throws Exception {
    assertThat(
      subject.bindValue(context, "://foo", URI.class),
      failedResult(equalIgnoringChildren(
          FileProblems.get().badUri("://foo", "Expected scheme name at index 0: ://foo")
      ))
    );
  }

}
