package com.atlassian.stash.internal.web.repos;

import com.atlassian.bitbucket.content.SimpleDirectory;
import com.atlassian.bitbucket.content.SimpleFile;
import com.atlassian.bitbucket.content.SimplePath;
import com.atlassian.bitbucket.content.SimpleSubmodule;
import com.atlassian.bitbucket.server.ApplicationPropertiesService;
import com.google.common.collect.Lists;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;

@RunWith(MockitoJUnitRunner.class)
public class ViewFileTest {

    private static final Function<ViewFile, String> TO_TYPE_NAME = input -> input.getType().toString().toLowerCase().charAt(0) + ":" + input.getName();

    @Mock
    private ApplicationPropertiesService applicationPropertiesService;

    @Test
    public void testSortFilesAlphabetically() {
        check(sort(file("a"), file("A"), file("b"), file("C"), file("d"), file("e")), "f:A", "f:a", "f:b", "f:C", "f:d", "f:e");
    }

    @Test
    public void testSortDirsAlphabetically() {
        check(sort(dir("a"), dir("A"), dir("b"), dir("C"), dir("d"), dir("e")), "d:A", "d:a", "d:b", "d:C", "d:d", "d:e");
    }

    @Test
    public void testSortDirsBeforeFilesAndSubmodules() {
        check(sort(dir("a"), file("e"), dir("A"), dir("b"), file("b"), sub("a"), file("A"), sub("C"), file("d"), dir("C"), dir("d"), dir("e")),
                "d:A", "d:a", "d:b", "d:C", "d:d", "d:e", "f:A", "s:a", "f:b", "s:C", "f:d", "f:e");
    }

    private ViewFile file(String name) {
        return new ViewFile(new SimpleFile.Builder().path(new SimplePath(name)).build(), "");
    }

    private ViewFile dir(String name) {
        return new ViewFile(new SimpleDirectory.Builder().path(new SimplePath(name)).build(), "");
    }

    private ViewFile sub(String name) {
        return new ViewFile(new SimpleSubmodule.Builder().path(new SimplePath(name)).url("").build());
    }

    private void check(List<ViewFile> sort, String... urls) {
        assertThat(sort.stream().map(TO_TYPE_NAME).collect(Collectors.toList()), is(Arrays.asList(urls)));
    }

    private List<ViewFile> sort(ViewFile... files) {
        List<ViewFile> list = Lists.newArrayList(files);
        Collections.sort(list);
        return list;
    }
}
