package com.atlassian.webdriver.bitbucket.element;

import com.atlassian.pageobjects.elements.PageElement;
import com.atlassian.pageobjects.elements.WebDriverLocatable;
import com.atlassian.pageobjects.elements.timeout.TimeoutType;
import com.atlassian.webdriver.bitbucket.page.ProjectOverviewPage;
import com.atlassian.webdriver.bitbucket.util.ElementUtils;
import com.atlassian.webdriver.bitbucket.util.Locators;
import org.openqa.selenium.By;

import java.util.List;

public class ProjectTable extends LegacyElementPageObject {

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

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

    public ProjectRow findProjectByName(String projectName) {

        for (ProjectRow row : getProjects()) {
            if (row.getProjectName().equals(projectName)) {
                return row;
            }
        }

        return null;
    }

    public List<ProjectRow> getProjects() {
        return findAll(Locators.tableRow(), ProjectRow.class);
    }

    public void loadNextPage() {
        ElementUtils.scrollDocumentAndWait(this);
    }

    public static class ProjectRow extends LegacyElementPageObject {

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

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

        public ProjectRow(WebDriverLocatable locatable, TimeoutType timeoutType) {
            super(locatable, timeoutType);
        }

        private PageElement getNameColumn() {
            return findAll(By.tagName("td")).get(0);
        }

        private PageElement getKeyColumn() {
            return findAll(By.tagName("td")).get(1);
        }

        private PageElement getDescriptionColumn() {
            return findAll(By.tagName("td")).get(2);
        }

        public String getProjectName() {
            return getNameColumn().getText();
        }

        public String getProjectKey() {
            return getKeyColumn().getText();
        }

        public String getProjectDescription() {
            return getDescriptionColumn().getText();
        }

        public ProjectOverviewPage goToProjectPage() {
            // Get the key before the page changes
            String projectKey = getProjectKey();

            getNameColumn().find(By.tagName("a")).click();

            return pageBinder.bind(ProjectOverviewPage.class, projectKey);
        }
    }
}
