package com.atlassian.webdriver.bitbucket.element;

import com.atlassian.pageobjects.elements.PageElement;
import org.openqa.selenium.By;

import javax.annotation.Nonnull;
import java.util.ArrayList;
import java.util.List;

/**
 * Represents the items from an {@link AppSwitcherDropdown}
 */
public class AppSwitcherDropdownItems extends AbstractElementPageObject {

    public AppSwitcherDropdownItems(@Nonnull PageElement container) {
        super(container);
    }

    /**
     * Gets a list of links in the dropdown.
     *
     * @return The list of items in the nav dropdown.
     */
    public List<String> getAppList() {
        List<PageElement> navLinks = getNavLinks();
        List<String> appList = new ArrayList<>(navLinks.size());
        for (PageElement navLink : navLinks) {
            appList.add(navLink.getText());
        }
        return appList;
    }

    /**
     * Clicks a link in the nav list.
     *
     * @param pageClass The page that will be loaded when you click the link.
     * @param displayName The name of the link to click.
     * @param <T> The class of the page that will be loaded.
     * @return The page object when the new page loads.
     */
    public <T> T clickLink(Class<T> pageClass, String displayName) {
        int listIndex = getAppList().indexOf(displayName);
        getNavLinks().get(listIndex).find(By.tagName("a")).click();
        return pageBinder.bind(pageClass);
    }

    /**
     * Gets a list of PageElements in the dropdown.
     *
     * @return The PageElements.
     */
    private List<PageElement> getNavLinks() {
        return container.findAll(By.className("nav-link"));
    }
}
