package com.atlassian.webdriver.bitbucket.element;

import com.atlassian.pageobjects.elements.PageElement;
import com.atlassian.pageobjects.elements.query.Poller;
import com.atlassian.pageobjects.elements.timeout.TimeoutType;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;

import java.util.Collection;
import java.util.Collections;

public class PullRequestTabs extends LegacyElementPageObject {

    public PullRequestTabs(PageElement pageElement) {
        super(pageElement);
    }

    public PullRequestTabs(By locator, TimeoutType timeoutType) {
        super(locator, timeoutType);
    }

    public Collection<TabItem> getTabItems() {
        try {
            return findAll(By.cssSelector(".aui-tabs > .tabs-menu > li"), TabItem.class, TimeoutType.PAGE_LOAD);
        } catch (NoSuchElementException e) {
            return Collections.emptyList();
        }
    }

    public TabItem getTab(String text) {
        for (TabItem tab : getTabItems()) {
            Poller.waitUntilTrue(tab.timed().isVisible());
            if (tab.getText().trim().equalsIgnoreCase(text.trim())) {
                return tab;
            }
        }
        throw new NoSuchElementException(text + " tab not found");
    }

    public void clickOverviewTab() {
        getTab("Overview").click();
    }

    public void clickDiffTab() {
        getTab("Diff").click();
    }

    public void clickCommitsTab() {
        getTab("Commits").click();
    }
}
