package com.atlassian.bitbucket.internal.key.ssh.condition;

import com.atlassian.bitbucket.project.Project;
import com.atlassian.bitbucket.repository.Repository;
import com.atlassian.bitbucket.ssh.SshAccessKeyService;
import com.atlassian.bitbucket.ssh.SshKey;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import java.util.Collections;

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

@RunWith(MockitoJUnitRunner.class)
public class ProjectHasSshAccessKeyConditionTest {
    private ProjectHasSshAccessKeyCondition condition;

    @Mock
    private Project project;
    @Mock
    private SshKey sshKey;
    @Mock
    private SshAccessKeyService sshKeyAccessService = null;

    @Before
    public void setUp() throws Exception {
        condition = new ProjectHasSshAccessKeyCondition(sshKeyAccessService);
        condition.init(Collections.<String, String>emptyMap());
    }

    @Test
    public void testNoProject() throws Exception {
        assertFalse(condition.shouldDisplay(Collections.<String, Object>emptyMap()));
    }

    @Test
    public void testHasSshKeyAccessEntriesButOnlyRepositoryAvailable() throws Exception {
        Repository repository = mock(Repository.class);
        when(repository.getProject()).thenReturn(project);
        when(sshKeyAccessService.existsForProject(same(project))).thenReturn(true);
        assertTrue(condition.shouldDisplay(Collections.<String, Object>singletonMap("repository", repository)));
    }

    @Test
    public void testNoSshKeyAccessEntries() throws Exception {
        assertFalse(condition.shouldDisplay(Collections.<String, Object>singletonMap("project", project)));
    }

    @Test
    public void testHasSshKeyAccessEntries() throws Exception {
        when(sshKeyAccessService.existsForProject(same(project))).thenReturn(true);
        assertTrue(condition.shouldDisplay(Collections.<String, Object>singletonMap("project", project)));
    }
}
