package com.atlassian.webdriver.bitbucket.element;

import com.atlassian.pageobjects.elements.ElementBy;
import com.atlassian.pageobjects.elements.PageElement;
import com.atlassian.pageobjects.elements.query.Poller;
import com.atlassian.pageobjects.elements.timeout.TimeoutType;
import com.atlassian.webdriver.bitbucket.page.PullRequestPage;
import org.openqa.selenium.By;

public class PullRequestMergeConfirmDialog<T extends PullRequestPage> extends Dialog2 {

    private final T page;

    @ElementBy(id = "commit-message")
    private PageElement commitMessageTextarea;

    @ElementBy(id = "delete-branch-checkbox")
    private PageElement deleteBranchCheckbox;

    @ElementBy(className = "confirm-button")
    private PageElement mergeButton;

    @ElementBy(id = "merge-strategy-button")
    private PageElement mergeStrategyDropDown;

    public PullRequestMergeConfirmDialog(By locatable, TimeoutType timeoutType, T page) {
        super(locatable, timeoutType);
        this.page = page;
    }

    public T confirmAndWaitForReload() {
        page.waitForPageLoad(new Runnable() {
            public void run() {
                mainActionButton.click();
            }
        });
        return page;
    }

    public T confirmMerge() {
        clickMainAction();
        return page;
    }

    public T confirmMergeExpectingWarning(By warningDialogLocator) {
        clickMainActionExpectingAnotherDialog();
        Dialog warningDialog = pageBinder.bind(Dialog.class, warningDialogLocator);
        Poller.waitUntilTrue(warningDialog.find(By.className("aui-message-warning")).timed().isVisible());
        warningDialog.clickCancel();
        return page;
    }

    public PageElement getDeleteBranchCheckbox() {
        return deleteBranchCheckbox;
    }

    public PageElement getMergeButton() {
        return mergeButton;
    }

    public PageElement getMergeStrategyDropDown() {
        return mergeStrategyDropDown;
    }

    public PullRequestMergeConfirmDialog<T> setCommitMessage(String msg) {
        commitMessageTextarea.type(msg);

        return this;
    }
}
