package com.atlassian.webdriver.bitbucket.element;

import com.atlassian.pageobjects.elements.PageElement;
import com.atlassian.pageobjects.elements.query.Poller;
import com.atlassian.pageobjects.elements.query.TimedCondition;
import com.atlassian.webdriver.bitbucket.util.ElementUtils;
import com.atlassian.webdriver.utils.by.ByDataAttribute;
import org.openqa.selenium.By;

import static com.atlassian.pageobjects.elements.query.Poller.waitUntilFalse;
import static com.atlassian.pageobjects.elements.query.Poller.waitUntilTrue;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;

public class SearchableSelectorDialog {

    private final PageElement dialog;

    public SearchableSelectorDialog(PageElement dialog) {
        this.dialog = checkNotNull(dialog, "dialog");
    }

    public SearchableSelectorDialog filterBy(final String filterText) {
        final PageElement filterInput = dialog.find(By.className("filter"));
        checkState(filterInput.isPresent(), "Searchable selector is not filterable");
        PageElement resultsList = dialog.find(By.className("results-list"));
        ElementUtils.waitUntilUpdated(resultsList, new Runnable() {
            @Override
            public void run() {
                filterInput.type(filterText);
            }
        });
        return this;
    }

    public TimedCondition isLoadingPage() {
        return dialog.find(By.className("spinner")).timed().isVisible();
    }

    public TimedCondition isOpen() {
        return dialog.timed().isVisible();
    }

    public int numberOfResults() {
        return dialog.findAll(By.className("result")).size();
    }

    public void selectItemByName(String itemName) {
        dialog.find(By.partialLinkText(itemName)).click();
        waitUntilFalse(dialog.timed().isVisible());
    }

    public void selectItemByExactName(String itemName) {
        dialog.find(By.linkText(itemName)).click();
        waitUntilFalse(dialog.timed().isVisible());
    }

    public void selectItemById(String dataId) {
        PageElement item = dialog.find(By.className("results")).find(ByDataAttribute.byData("id", dataId));
        waitUntilTrue(item.timed().isVisible());
        item.javascript().form().focus();
        item.click();
        waitUntilFalse(dialog.timed().isVisible());
    }

    public SearchableSelectorDialog selectBranches() {
        return selectTab("Branches");
    }

    public SearchableSelectorDialog selectTags() {
        return selectTab("Tags");
    }

    private SearchableSelectorDialog selectTab(String linkText) {
        PageElement tab = dialog.find(By.linkText(linkText)).click(); // brittle but there is no distinguishing CSS class or id to rely on
        Poller.waitUntilTrue(tab.timed().hasAttribute("aria-selected", "true"));
        return this;
    }

}
