package com.atlassian.stash.internal.scm.git.protocol.http;

import com.atlassian.bitbucket.i18n.SimpleI18nService;
import com.atlassian.stash.internal.scm.git.GitRepositoryTypeCheck;
import com.atlassian.stash.internal.scm.git.protocol.ssh.GitSshScmRequest;
import com.atlassian.bitbucket.repository.Repository;
import com.atlassian.bitbucket.scm.ScmRequest;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import static org.hamcrest.Matchers.containsString;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.argThat;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

@RunWith(MockitoJUnitRunner.class)
public class GitRepositoryTypeCheckTest {

    @Mock
    private ScmRequest request;
    @Mock
    private GitSmartRequest gitRequest;
    @Mock
    private GitSshScmRequest sshScmRequest;
    @Mock
    private Repository repository;

    private final GitRepositoryTypeCheck check = new GitRepositoryTypeCheck(new SimpleI18nService());

    @Test
    public void testNotAGitRequest() throws Exception {
        assertTrue(check.check(request));
    }

    @Test
    public void testNoRepository() throws Exception {
        assertTrue(check.check(gitRequest));
    }

    @Test
    public void testNoRepositoryDefinedInSshRequest() throws Exception {
        assertTrue(check.check(sshScmRequest));
    }

    @Test
    public void testNonGitRepository() throws Exception {
        when(repository.getScmId()).thenReturn("cvs-oh-my");
        when(gitRequest.getRepository()).thenReturn(repository);
        assertFalse(check.check(gitRequest));
        verify(gitRequest).sendError(argThat(containsString("bitbucket.scm.git.repository.unsupported")),
                argThat(containsString("bitbucket.scm.git.repository.unsupported.detail")));
    }

    @Test
    public void testNonGitRepositoryForSshRequest() throws Exception {
        when(repository.getScmId()).thenReturn("cvs-oh-my");
        when(sshScmRequest.getRepository()).thenReturn(repository);
        assertFalse(check.check(sshScmRequest));
        verify(sshScmRequest).sendError(argThat(containsString("bitbucket.scm.git.repository.unsupported")),
                argThat(containsString("bitbucket.scm.git.repository.unsupported.detail")));
    }

    @Test
    public void testGitRepository() throws Exception {
        when(gitRequest.getRepository()).thenReturn(repository);
        when(repository.getScmId()).thenReturn("git");
        assertTrue(check.check(gitRequest));
    }

    @Test
    public void testGitRepositoryForSsh() throws Exception {
        when(sshScmRequest.getRepository()).thenReturn(repository);
        when(repository.getScmId()).thenReturn("git");
        assertTrue(check.check(sshScmRequest));
    }

}
