package com.atlassian.bitbucket.internal.integration.jira.idx;

import com.atlassian.bitbucket.integration.jira.JiraConstants;
import com.atlassian.integration.jira.JiraKeyScanner;
import com.atlassian.bitbucket.commit.Commit;
import com.atlassian.bitbucket.idx.CommitIndex;
import com.atlassian.bitbucket.idx.IndexingContext;
import com.atlassian.bitbucket.repository.Repository;
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 static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.*;

@RunWith(MockitoJUnitRunner.class)
public class JiraKeyIndexerTest {

    @Mock
    private CommitIndex commitIndex;
    @Mock
    private IndexingContext indexingContext;
    @InjectMocks
    private JiraKeyIndexer indexer;
    @Mock
    private Repository repository;
    @Mock
    private JiraKeyScanner scanner;

    @Test
    public void testGetId() {
        assertEquals(JiraKeyIndexer.ID, indexer.getId());
    }

    @SuppressWarnings("ConstantConditions")
    @Test
    public void testIsEnabledForRepository() {
        assertTrue(indexer.isEnabledForRepository(repository));
        assertTrue(indexer.isEnabledForRepository(null)); //Doesn't check null
    }

    @Test
    public void testOnAfterIndexing() {
        indexer.onAfterIndexing(indexingContext);

        verifyZeroInteractions(commitIndex, indexingContext);
    }

    @Test
    public void testOnBeforeIndexing() {
        indexer.onBeforeIndexing(indexingContext);

        verifyZeroInteractions(commitIndex);
    }

    @Test
    public void testOnCommitAdded() {
        when(scanner.findAll(eq("STASH-2471  Some commit message"))).thenReturn(Collections.singleton("stash-2471"));

        Commit commit = mockCommit("STASH-2471  Some commit message");
        when(commit.getId()).thenReturn("id");

        indexer.onCommitAdded(commit, indexingContext);

        verify(commitIndex).addProperty(eq("id"), same(JiraConstants.IDX_PROP_ISSUE_KEYS), eq("STASH-2471"));
    }

    @Test
    public void testOnCommitAddedNoKey() {
        when(scanner.findAll(eq("This message has no key"))).thenReturn(Collections.<String>emptyList());

        indexer.onCommitAdded(mockCommit("This message has no key"), indexingContext);

        verifyZeroInteractions(commitIndex);
    }

    @Test
    public void testOnCommitRemoved() {
        indexer.onCommitRemoved(mock(Commit.class), indexingContext);

        verifyZeroInteractions(commitIndex, indexingContext);
    }

    private Commit mockCommit(String message) {
        Commit commit = mock(Commit.class);
        when(commit.getMessage()).thenReturn(message);

        return commit;
    }
}
