package com.atlassian.bitbucket.plugin;

import com.atlassian.plugin.PluginAccessor;
import com.atlassian.bitbucket.scm.BaseWeightedModuleDescriptor;
import com.google.common.collect.Lists;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;

import java.util.List;

import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

public class ModuleDescriptorTestUtils {

    public static <D extends BaseWeightedModuleDescriptor<M>, M> void mockWeightedModuleDescriptors(
            PluginAccessor pluginAccessor, Class<D> moduleDescriptorClass, M... modules) {

        final List<D> descriptors = Lists.newArrayList();

        for (M module : modules) {
            D descriptor = mock(moduleDescriptorClass);
            when(descriptor.getModule()).thenReturn(module);

            // mock sort order to match the order of the provided handlers
            when(descriptor.compareTo(any(moduleDescriptorClass)))
                    .thenAnswer(invocationOnMock -> {
                        int thisIndex = descriptors.indexOf(invocationOnMock.getMock());
                        int otherIndex = descriptors.indexOf(invocationOnMock.getArguments()[0]);

                        return thisIndex -  otherIndex;
                    });

            descriptors.add(descriptor);
        }

        when(pluginAccessor.getEnabledModuleDescriptorsByClass(eq(moduleDescriptorClass))).thenReturn(descriptors);
    }
}
