package it.com.atlassian.stash.pull;

import com.atlassian.pageobjects.elements.query.Poller;
import com.atlassian.webdriver.bitbucket.element.PullRequestMergeConfirmDialog;
import com.atlassian.webdriver.bitbucket.element.activity.MergeActivityItem;
import com.atlassian.webdriver.bitbucket.page.ChangesetUnifiedDiffPage;
import com.atlassian.webdriver.bitbucket.page.PullRequestOverviewPage;
import com.google.common.collect.Iterables;
import it.com.atlassian.stash.rules.WebStorageCleanUpRule;
import org.hamcrest.Matchers;
import org.junit.Test;
import org.junit.rules.TestRule;

import java.util.List;

import static com.atlassian.bitbucket.test.TestRuleOrderingSyntax.outerRules;
import static org.junit.Assert.assertThat;

public class PullRequestMergeCommitMessageTest extends BasePullRequestFuncTest {

    @Test
    public void testMergeWithCommitMessage() {
        String commitMessage = "Custom commit \"message";

        PullRequestOverviewPage pullRequestPage = createPullRequestAndLogin(BRANCH_THAT_HAS_SAME_FILE_MODIFIED_AND_MOVED_SRC,
                MASTER);

        PullRequestMergeConfirmDialog pullRequestMergeDialog = pullRequestPage.getMergeButton().clickButton();
        pullRequestMergeDialog.setCommitMessage(commitMessage);
        pullRequestMergeDialog.confirmMerge();

        Poller.waitUntil("Merge activity should be added",
                pullRequestPage.getActivitiesOfType(MergeActivityItem.class),
                Matchers.<MergeActivityItem>iterableWithSize(1));
        MergeActivityItem activity = Iterables.getFirst(pullRequestPage.getActivitiesOfType(MergeActivityItem.class).now(), null);
        String mergeCommitId = activity.getCommitId();
        activity.openMergeCommitPage();

        ChangesetUnifiedDiffPage changesetPage = BITBUCKET.getPageBinder().bind(ChangesetUnifiedDiffPage.class,
                PROJECT_KEY, REPO_SLUG, mergeCommitId);
        assertThat("Custom commit message that includes a single, unclosed double quote", changesetPage.getMetadata()
                .getMessage(), Matchers.containsString(commitMessage));
    }

    @Override
    protected List<TestRule> getRetryRuleChain() {
        return outerRules(new WebStorageCleanUpRule()).around(super.getRetryRuleChain());
    }
}
