package com.atlassian.stash.internal.web.pull.task;

import com.atlassian.stash.internal.pull.InternalPullRequest;
import com.atlassian.stash.internal.pull.InternalPullRequestRef;
import com.atlassian.stash.internal.repository.InternalRepository;
import com.atlassian.stash.internal.task.InternalTaskCount;
import com.atlassian.bitbucket.pull.PullRequestService;
import com.atlassian.bitbucket.task.TaskState;
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.Map;

import static com.atlassian.bitbucket.task.TaskMatchers.hasContext;
import static org.hamcrest.Matchers.hasEntry;
import static org.junit.Assert.assertThat;
import static org.mockito.Matchers.argThat;
import static org.mockito.Mockito.when;

@RunWith(MockitoJUnitRunner.class)
public class PullRequestTaskPageProviderTest {

    private static final InternalRepository REPOSITORY = new InternalRepository.Builder().id(999)
            .name("repository")
            .build();
    private static final InternalPullRequest PULL_REQUEST = new InternalPullRequest.Builder().scopedId(999L)
            .toRef(new InternalPullRequestRef.Builder()
                    .repository(REPOSITORY)
                    .build())
            .build();

    @Mock
    private PullRequestService pullRequestService;

    @InjectMocks
    private PullRequestTaskPageProvider pullRequestTaskPageProvider;

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

        when(pullRequestService.countTasks(argThat(hasContext(PULL_REQUEST))))
                .thenReturn(new InternalTaskCount(ImmutableMap.of(TaskState.OPEN, 5L, TaskState.RESOLVED, 7L)));

        Map<String, Object> attributes = pullRequestTaskPageProvider.getContextMap(context);

        assertThat(attributes, hasEntry("openTaskCount", (Object) 5L));
        assertThat(attributes, hasEntry("resolvedTaskCount", (Object) 7L));
    }

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

        when(pullRequestService.countTasks(argThat(hasContext(PULL_REQUEST))))
                .thenReturn(new InternalTaskCount(ImmutableMap.<TaskState, Long>of()));

        Map<String, Object> attributes = pullRequestTaskPageProvider.getContextMap(context);

        assertThat(attributes, hasEntry("openTaskCount", (Object) 0L));
        assertThat(attributes, hasEntry("resolvedTaskCount", (Object) 0L));
    }
}