package com.atlassian.webdriver.bitbucket.element.tasks;

import com.atlassian.pageobjects.binder.WaitUntil;
import com.atlassian.pageobjects.elements.PageElement;
import com.atlassian.pageobjects.elements.PageElementFinder;
import com.atlassian.pageobjects.elements.query.Poller;
import com.atlassian.pageobjects.elements.timeout.TimeoutType;
import com.atlassian.webdriver.bitbucket.element.Dialog2;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;

import javax.inject.Inject;

public class PullRequestTaskListDialog extends Dialog2 {

    public static final String CLASS = "task-list-dialog";

    @Inject
    PageElementFinder pageElementFinder;

    public PullRequestTaskListDialog() {
        super(By.className(CLASS), TimeoutType.DIALOG_LOAD);
    }

    public void close() {
        // typing directly into the dialog fails because the element is not visible, so we target the page body instead
        pageElementFinder.find(By.tagName("body")).type(Keys.ESCAPE);
        waitUntilDismissed();
        waitUntilBlanketHidden();
    }

    public int getTaskCount() {
        return getTaskTable().size();
    }

    public boolean isEmpty() {
        PageElement emptyTableMessage = find(By.className("paged-table-message"));
        Poller.waitUntilTrue("Task list is empty", emptyTableMessage.timed().isVisible());
        return true;
    }

    public TaskTable.Row getRowByCommentId(long id) {
        return getTaskTable().getRowByCommentId(id);
    }

    public TaskTable.Row getRowAt(int i) {
        return getTaskTable().getRowAt(i);
    }

    private TaskTable getTaskTable() {
        return pageBinder.bind(TaskTable.class);
    }

    @WaitUntil
    private void isLoaded() {
        Poller.waitUntilFalse(find(By.className("spinner")).timed().isVisible());
    }

}
