package com.atlassian.bitbucket.mesh.git.builder.lstree;

import com.atlassian.bitbucket.mesh.AbstractWiredTest;
import com.atlassian.bitbucket.mesh.git.GitRepositories;
import com.atlassian.bitbucket.mesh.git.builder.GitProcessBuilderFactory;
import com.atlassian.bitbucket.mesh.git.content.Directory;
import com.atlassian.bitbucket.mesh.repository.Repository;
import com.atlassian.bitbucket.mesh.test.annotation.Repo;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

public class CollapsingDirectoryCreatorTest extends AbstractWiredTest {

    @Autowired
    private GitProcessBuilderFactory builderFactory;
    private CollapsingDirectoryCreator creator;
    @Repo(GitRepositories.QA_RESOURCES)
    private Repository repository;

    @Before
    public void setup() {
        creator = new CollapsingDirectoryCreator(builderFactory, repository);
    }

    @After
    public void tearDown() {
        if (creator != null) {
            creator.close();
        }
    }

    @Test
    public void testCreateCollapses() {
        //This is master:Calculator/src/main. It has only a single subdirectory, "java", and so it
        //should be collapsed. "java" only has an "org" subdirectory, which only has a "farmas"
        //subdirectory. Those should be collapsed. "farmas" contains a single file, which should
        //not be collapsed because it's not a directory
        Directory main = creator.create("main", "ccf6b5877445faf95105f873d03b38e05b549a6b");
        assertEquals("main/java/org/farmas", main.getPath());
        assertEquals("887da8ccd5700f0320ae84a76ee04d988d171dd5", main.getContentId());

        //This is the sibling "test" directory, which has a similar layout
        Directory test = creator.create("test", "ce8531443b4093935498273ca0617ccafbaf71b8");
        assertEquals("test/java/org", test.getPath());
        assertEquals("2f35f36f28916a33c28c90450c6897423f9e182f", test.getContentId());
    }

    @Test
    public void testCreateDoesNotCollapseWithMultipleSubdirectories() {
        //This is master:Calculator/src. It has two subdirectories, so it won't collapse
        Directory directory = creator.create("src", "a087f35258896edcf90cf266e7a05789bcd4eb88");
        assertEquals("src", directory.getPath());
        assertEquals("a087f35258896edcf90cf266e7a05789bcd4eb88", directory.getContentId());
    }

    @Test
    public void testCreateIgnoresMissing() {
        //This is 15ab4945f5d8d3cf5f3cd92e16ccd9a1398e28a4:api from STASH/stash. It doesn't exist
        //in qa-resources, so it should be ignored.
        Directory directory = creator.create("api", "c43cb3c7a1a04a9325a930aefa75be1166c82048");
        assertEquals("api", directory.getPath());
        assertEquals("c43cb3c7a1a04a9325a930aefa75be1166c82048", directory.getContentId());
    }
}