package com.atlassian.stash.internal.web.fragments;

import com.atlassian.bitbucket.commit.Commit;
import com.atlassian.stash.internal.watcher.InternalWatcherService;
import com.atlassian.bitbucket.auth.AuthenticationContext;
import com.atlassian.bitbucket.user.ApplicationUser;
import com.atlassian.bitbucket.watcher.Watchable;
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 IsWatchingContextProviderTest {

    @Mock
    private AuthenticationContext authenticationContext;
    @Mock
    private ApplicationUser author;
    @Mock
    private Commit commit;
    @InjectMocks
    private IsWatchingContextProvider isWatchingContextProvider;
    @Mock
    private Watchable watchable;
    @Mock
    private InternalWatcherService watcherService;

    @Test
    public void testWithWatchable() {
        ImmutableMap.Builder<String, Object> builder = ImmutableMap.builder();
        builder.put("watchable", watchable);
        when(authenticationContext.getCurrentUser()).thenReturn(author);
        when(watcherService.isCurrentUserWatching(watchable)).thenReturn(true);

        Map<String, Object> context = isWatchingContextProvider.getContextMap(builder.build());
        assertTrue((Boolean) context.get("isWatching"));
    }

    @Test
    public void testUserIsCommitAuthor() {
        ImmutableMap.Builder<String, Object> builder = ImmutableMap.builder();
        builder.put("commit", commit);
        when(authenticationContext.getCurrentUser()).thenReturn(author);
        when(author.getEmailAddress()).thenReturn("user@test.com");
        when(commit.getAuthor()).thenReturn(author);

        Map<String, Object> context = isWatchingContextProvider.getContextMap(builder.build());
        assertTrue((Boolean) context.get("isWatching"));
    }

    @Test
    public void testAnonymousUser() {
        ImmutableMap.Builder<String, Object> builder = ImmutableMap.builder();
        builder.put("commit", commit);
        when(authenticationContext.getCurrentUser()).thenReturn(null);

        Map<String, Object> context = isWatchingContextProvider.getContextMap(builder.build());
        assertFalse((Boolean) context.get("isWatching"));
    }

    @Test
    public void testNoContextParams() {
        Map<String, Object> context = isWatchingContextProvider.getContextMap(Collections.<String, Object>emptyMap());
        assertFalse((Boolean) context.get("isWatching"));
    }
}
