package com.atlassian.bitbucket.mesh.layout;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.core.env.Environment;

import java.io.IOException;
import java.nio.file.InvalidPathException;
import java.nio.file.Path;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThrows;
import static org.mockito.Mockito.when;

@RunWith(MockitoJUnitRunner.class)
public class DefaultHomeSubdirectoryResolverTest {

    @Rule
    public final TemporaryFolder temporaryFolder = new TemporaryFolder();

    @Mock
    private Environment environment;
    @InjectMocks
    private DefaultHomeSubdirectoryResolver subdirectoryResolver;

    @Test
    public void testResolveWithDefaults() throws IOException {
        Path homeDir = mkdir("home-dir");

        Path actualTmpDir = subdirectoryResolver.resolve(homeDir, "caches");
        assertEquals(homeDir.resolve("caches"), actualTmpDir);
    }

    @Test
    public void testResolveWithFileThrows() throws IOException {
        Path homeDir = mkdir("home-dir");
        Path file = temporaryFolder.newFile().toPath();
        when(environment.getProperty("layout.caches-dir")).thenReturn(file.toString());

        assertThrows(IllegalStateException.class, () -> subdirectoryResolver.resolve(homeDir, "caches"));
    }

    @Test
    public void testResolveWithInvalidOverrideThrows() throws IOException {
        Path homeDir = mkdir("home-dir");
        when(environment.getProperty("layout.caches-dir")).thenReturn("\0-null-char-is-invalid");

        assertThrows(InvalidPathException.class, () -> subdirectoryResolver.resolve(homeDir, "caches"));
    }

    @Test
    public void testResolveWithOverride() throws IOException {
        Path homeDir = mkdir("home-dir");
        Path cacheDir = mkdir("caches-dir");
        when(environment.getProperty("layout.caches-dir")).thenReturn(cacheDir.toAbsolutePath().toString());

        Path actual = subdirectoryResolver.resolve(homeDir, "caches");
        assertEquals(cacheDir, actual);
    }

    private Path mkdir(String name) throws IOException {
        return temporaryFolder.newFolder(name).toPath();
    }
}