package com.atlassian.bitbucket.mesh.git.submodule;

import com.atlassian.bitbucket.mesh.AbstractWiredTest;
import com.atlassian.bitbucket.mesh.git.GitRepositories;
import com.atlassian.bitbucket.mesh.repository.Repository;
import com.atlassian.bitbucket.mesh.repository.RepositoryManager;
import com.atlassian.bitbucket.mesh.test.annotation.Repo;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

public class DefaultSubmoduleManagerTest extends AbstractWiredTest {

    private static final String CONTENT_ID = "abc1234";

    @Autowired
    private DefaultSubmoduleManager manager;
    @Autowired
    private RepositoryManager repositoryManager;
    @Repo
    private Repository sanity;
    @Repo(GitRepositories.SUBREPOSITORIES)
    private Repository submodules;

    @Test
    public void testGet() {
        Submodules submodules = manager.get(this.submodules, "ecf42d8adc4d7eb4386e37882d053704067712d4", "submodule");
        assertNotNull(submodules);
        assertSubmodule(submodules, "atlassian-refapp", "git@bitbucket.org:atlassian/atlassian-refapp.git");
        assertSubmodule(submodules, "bamboo-git-plugin", "git@github.com:atlassian/bamboo-git-plugin.git");
        assertSubmodule(submodules, "stash", "/home/user/fake/repo");
        assertNull(submodules.get("nonexistent", CONTENT_ID));
    }

    @Test
    public void testGetUnconfigured() {
        //This repository has no submodules, and no .gitmodules file. Getting a Submodules instance
        //should return non-null, but it shouldn't return anything. Most importantly, no exceptions
        //should be thrown
        Submodules submodules = manager.get(sanity, "master", null);
        assertNotNull("A Submodules instance should still be returned", submodules);
        assertNull(submodules.get("basic_branching", CONTENT_ID));
    }

    private static void assertSubmodule(Submodules submodules, String path, String url) {
        Submodule submodule = submodules.get(path, CONTENT_ID);
        assertNotNull(path + " was not found", submodule);
        assertEquals(path + " has an unexpected path", path, submodule.getPath());
        assertEquals(path + " has an unexpected content ID", CONTENT_ID, submodule.getContentId());
        assertEquals(path + " has an unexpected URL", url, submodule.getUrl());
        assertTrue(path + " is not active", submodule.isActive());
    }
}