package com.atlassian.bitbucket.web.conditions;

import com.atlassian.plugin.PluginParseException;
import com.atlassian.bitbucket.repository.Repository;
import com.google.common.collect.ImmutableMap;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import java.util.Collections;
import java.util.Map;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.when;

@RunWith(MockitoJUnitRunner.class)
public class IsScmConditionTest {

    @InjectMocks
    private IsScmCondition condition;
    @Mock
    private Repository repository;

    @Test(expected = PluginParseException.class)
    public void testInitWithBlankScm() {
        condition.init(ImmutableMap.of("scm", "\n\t    "));
    }

    @Test(expected = PluginParseException.class)
    public void testInitWithEmptyContext() throws Exception {
        condition.init(Collections.<String, String>emptyMap());
    }

    @Test(expected = PluginParseException.class)
    public void testInitWithEmptyScm() {
        condition.init(ImmutableMap.of("scm", ""));
    }

    @Test(expected = PluginParseException.class)
    public void testInitWithNullScm() {
        condition.init(Collections.<String, String>singletonMap("scm", null));
    }

    @Test
    public void testShouldDisplay() throws Exception {
        Map<String, Object> context = ImmutableMap.<String, Object>of("repository", repository);

        condition.init(ImmutableMap.of("scm", "test"));

        //If there's no repository, the condition should not display
        assertFalse(condition.shouldDisplay(Collections.<String, Object>emptyMap()));

        //If the SCMs don't match, the condition should not display
        when(repository.getScmId()).thenReturn("git");
        assertFalse(condition.shouldDisplay(context));

        when(repository.getScmId()).thenReturn("test");
        assertTrue(condition.shouldDisplay(context));
    }

    @Test
    public void testShouldDisplayWithCustomKey() throws Exception {
        Map<String, Object> context = ImmutableMap.<String, Object>of("upstream", repository);

        condition.init(ImmutableMap.of("key", "upstream", "scm", "test"));

        //If there's no repository, the condition should not display
        assertFalse(condition.shouldDisplay(Collections.<String, Object>emptyMap()));

        //When the repository is under a different key the condition should not display
        assertFalse(condition.shouldDisplay(ImmutableMap.<String, Object>of("upstream", repository)));

        //If the SCMs don't match, the condition should not display
        when(repository.getScmId()).thenReturn("git");
        assertFalse(condition.shouldDisplay(context));

        when(repository.getScmId()).thenReturn("test");
        assertTrue(condition.shouldDisplay(context));
    }
}