package com.atlassian.stash.internal.scm.git.submodule;

import com.atlassian.bitbucket.nav.NavBuilder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Answers;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import java.net.URI;

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

@RunWith(MockitoJUnitRunner.class)
public class DefaultGitSubmoduleUriHandlerTest {

    @Mock(answer = Answers.RETURNS_DEEP_STUBS)
    private NavBuilder navBuilder;

    @Test
    public void testSSH() {
        process("ssh://example.com:7999/PROJECT/repo");
    }

    @Test
    public void testHttp() {
        process("http://example.com:7990/bitbucket/PROJECT/repo");
    }

    @Test
    public void testFile() {
        when(navBuilder.buildBaseUrl()).thenReturn("https://example.com:7990/bitbucket");
        assertEquals(SubmoduleUrls.NONE, createURIHandler().process(URI.create("/some/file/patch"), "hash"));
    }

    @Test
    public void testShortURI() {
        when(navBuilder.buildBaseUrl()).thenReturn("https://example.com:7990/bitbucket");
        assertEquals(SubmoduleUrls.NONE, createURIHandler().process(URI.create("http://example.com:7990/short"), "hash"));
    }

    private void process(String uri) {
        String base = "https://example.com:7990/bitbucket";
        when(navBuilder.buildBaseUrl()).thenReturn(base);
        mockNavBuilder(base, "PROJECT", "repo", "hash");
        SubmoduleUrls urls = createURIHandler().process(URI.create(uri), "hash");
        assertEquals(base + "/projects/PROJECT/repos/repo", urls.getRepositoryUrl());
        assertEquals(base + "/projects/PROJECT/repos/repo/browse?at=hash", urls.getBrowseUrl());
    }

    private DefaultGitSubmoduleUriHandler createURIHandler() {
        return new DefaultGitSubmoduleUriHandler(navBuilder);
    }

    private void mockNavBuilder(String base, String project1, String repoSlug, String at) {
        when(navBuilder.project(project1).repo(repoSlug).browse().atRevision(at).buildAbsolute()).thenReturn(base + "/projects/" + project1 + "/repos/" + repoSlug + "/browse?at=" + at);
        when(navBuilder.project(project1).repo(repoSlug).buildAbsolute()).thenReturn(base + "/projects/" + project1 + "/repos/" + repoSlug);
    }

}
