package com.atlassian.bitbucket.util;

import com.atlassian.bitbucket.scm.BaseWeightedModuleDescriptor;
import com.atlassian.plugin.ModuleDescriptor;
import com.atlassian.plugin.module.ModuleFactory;
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.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static com.atlassian.bitbucket.util.ModuleDescriptorUtils.toSortedModules;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

@RunWith(MockitoJUnitRunner.class)
public class ModuleDescriptorUtilsTest {

    @Mock
    private ModuleDescriptor<String> moduleDescriptor;

    @Test
    public void testToModule() throws Exception {
        when(moduleDescriptor.getModule()).thenReturn("FooModule");
        assertThat(ModuleDescriptorUtils.<String, ModuleDescriptor<String>>toModule().apply(moduleDescriptor), is("FooModule"));
    }

    @Test
    public void testToModules() throws Exception {
        when(moduleDescriptor.getModule()).thenReturn("FooModule");
        Optional<String> maybeModule = ModuleDescriptorUtils.toModules(Stream.of(moduleDescriptor)).findFirst();
        assertThat(maybeModule.get(), is("FooModule"));
    }

    @Test
    public void testToSortedModules() throws Exception {
        List<BaseWeightedModuleDescriptor<String>> moduleDescriptors = Arrays.asList(
                weightedModuleDescriptor("Module1", 100),
                weightedModuleDescriptor("Module2", 5),
                weightedModuleDescriptor("Module3", 200)
        );

        assertThat(toSortedModules(moduleDescriptors).collect(Collectors.toList()), contains("Module2", "Module1", "Module3"));
    }

    private static <T> BaseWeightedModuleDescriptor<T> weightedModuleDescriptor(T module, int weight) {
        ModuleFactory moduleFactory = mock(ModuleFactory.class);
        return new BaseWeightedModuleDescriptor<T>(moduleFactory, weight) {
            @Override
            public T getModule() {
                return module;
            }
        };
    }
}