package it.com.atlassian.stash.tasks;

import com.atlassian.bitbucket.test.DefaultFuncTestData;
import com.atlassian.bitbucket.test.PullRequestTestHelper;
import com.atlassian.pageobjects.elements.query.Poller;
import com.atlassian.webdriver.bitbucket.page.*;
import it.com.atlassian.stash.BaseBrowserFuncTest;
import org.junit.After;
import org.junit.Before;

public abstract class BasePullRequestTaskUITest extends BaseBrowserFuncTest {

    protected static final String PROJECT = DefaultFuncTestData.getProject1();
    protected static final String REPO = DefaultFuncTestData.getProject1Repository1();
    protected static final String USER = DefaultFuncTestData.getAdminUser();
    protected static final String USER_PASSWORD = DefaultFuncTestData.getAdminPassword();
    protected static final String TASK_TEXT = "This is a task";
    protected static final String TASK_TEXT2 = "This is a different task";

    protected PullRequestTestHelper pullRequest;

    @Before
    public void setUp() throws Exception {
        loginAsAdmin(AboutPage.class);
        pullRequest = testContext.pullRequest(new PullRequestTestHelper.Builder(
                USER, USER_PASSWORD, "automated test", "",
                PROJECT, REPO, "basic_branching",
                PROJECT, REPO, "master"));
        pullRequest.addGeneralComment("a comment");
        pullRequest.addGeneralComment("another comment");
        pullRequest.addGeneralComment("third comment");
    }

    @After
    public void tearDown() throws Exception {
        pullRequest.declineSafe();
    }

    protected PullRequestOverviewPage goToPullRequest(PullRequestTestHelper pullRequest) {
        PullRequestOverviewPage pullRequestOverviewPage = goToRepositoryPage(PullRequestOverviewPage.class, pullRequest.getId());
        Poller.waitUntilTrue(pullRequestOverviewPage.isHereTimed());
        return pullRequestOverviewPage;
    }

    protected PullRequestEffectiveDiffPage goToPullRequestDiff(PullRequestTestHelper pullRequest) {
        PullRequestEffectiveDiffPage pullRequestDiffPage = goToRepositoryPage(PullRequestEffectiveDiffPage.class, pullRequest.getId());
        Poller.waitUntilTrue(pullRequestDiffPage.isHereTimed());
        return pullRequestDiffPage;
    }

    protected PullRequestListPage goToPullRequestList() {
        PullRequestListPage pullRequestListPage = goToRepositoryPage(PullRequestListPage.class);
        Poller.waitUntilTrue(pullRequestListPage.isHereTimed());
        return pullRequestListPage;
    }

    private <P extends BaseRepositoryPage> P goToRepositoryPage(Class<P> pageClass) {
        return BITBUCKET.visit(pageClass, PROJECT, REPO);
    }

    private <P extends BaseRepositoryPage> P goToRepositoryPage(Class<P> pageClass, Object context) {
        return BITBUCKET.visit(pageClass, PROJECT, REPO, context);
    }
}
