package com.atlassian.stash.internal.scm.git.command.merge;

import com.atlassian.bitbucket.i18n.I18nService;
import com.atlassian.bitbucket.i18n.SimpleI18nService;
import com.atlassian.bitbucket.project.Project;
import com.atlassian.bitbucket.repository.Repository;
import com.atlassian.bitbucket.scm.git.command.push.GitNonFastForwardUpdateRejectedException;
import com.google.common.io.CharStreams;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.core.io.ClassPathResource;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import static org.mockito.Mockito.when;

@RunWith(MockitoJUnitRunner.class)
public class FetchCommandExitHandlerTest {

    private I18nService i18nService;
    @Mock
    private Project project;
    @Mock
    private Repository repository;

    @Before
    public void setup() {
        i18nService = new SimpleI18nService();

        when(project.getKey()).thenReturn("KEY");

        when(repository.getProject()).thenReturn(project);
        when(repository.getSlug()).thenReturn("slug");
    }

    @Test(expected = GitNonFastForwardUpdateRejectedException.class)
    public void testEvaluateStdErrForNonFastForwardForcedPush() throws Exception {
        runTest(true);
    }

    @Test(expected = GitNonFastForwardUpdateRejectedException.class)
    public void testEvaluateStdErrForNonFastForwardPush() throws Exception {
        runTest(false);
    }

    private void runTest(boolean forced) throws Exception {
        InputStream stream = new ClassPathResource("git-fetch-non-fast-forward.out", getClass()).getInputStream();
        String stdErr = CharStreams.toString(new BufferedReader(new InputStreamReader(stream)));

        new FetchCommandExitHandler(i18nService, repository, "refs/pull-requests/1/merge", forced)
                .evaluateStdErr(stdErr, "git fetch");
    }
}
