package net.ranides.assira.io.uri.impl;

import org.junit.Assume;
import org.junit.Test;

import net.ranides.assira.io.uri.URIBuilder;
import net.ranides.assira.io.uri.URIHandle;
import net.ranides.assira.io.uri.URIResolver;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URI;

import static net.ranides.assira.junit.NewAssert.assertThrows;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

/**
 * @author msieron
 */
public class CDirHandlerTest {

    private static URIHandle resolve(URI uri) throws IOException {
        return new CFileHandler().resolve(uri);
    }

    private static URIBuilder uri(String file) {
        return new URIBuilder(new File(file).toURI());
    }

    @Test
    public void testCustomDir() throws IOException {
        URIResolver resolver = new URIResolver()
            .register(r -> new CDirHandler(r, "tr","src/test/resources"));

        assertTrue(resolver.resolve("tr://xml/input.xml").exists());
        assertFalse(resolver.resolve("tr://xml/unknown.xml").exists());

        assertThrows(FileNotFoundException.class, () -> {
            assertFalse(resolver.resolve("tr://xml/../../../illegal.xml").exists());
        });

    }

    @Test
    public void testDefaultDir() throws IOException {
        URIResolver resolver = URIResolver.DEFAULT;

        assertTrue(resolver.resolve("test://xml/input.xml").exists());
        assertFalse(resolver.resolve("test://xml/unknown.xml").exists());

        assertThrows(FileNotFoundException.class, () -> {
            assertFalse(resolver.resolve("test://xml/../../../illegal.xml").exists());
        });
    }

    @Test
    public void testHomeDir() throws IOException {
        URIResolver resolver = URIResolver.DEFAULT;
        Assume.assumeTrue(resolver.resolve("home://.m2").exists());
        Assume.assumeTrue(resolver.resolve("home://.bash_history").exists());
    }

}