package it.com.atlassian.stash.defaultreviewers.page;

import com.atlassian.pageobjects.elements.ElementBy;
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.page.BaseRepositoryPage;
import org.openqa.selenium.By;

import java.util.Collections;
import java.util.List;

import static com.atlassian.webdriver.bitbucket.util.ElementUtils.bind;
import static java.util.stream.Collectors.toList;

public class DefaultReviewersPage extends BaseRepositoryPage {
    @ElementBy(id = "add-default-reviewer-button")
    private PageElement addButton;
    @ElementBy(id = "add-default-reviewer-button-empty-state")
    private PageElement addButtonEmptyState;
    @ElementBy(className = "first-contact-content")
    private PageElement firstContactScreen;
    @ElementBy(id="default-reviewers-table")
    private PageElement ruleTable;

    public DefaultReviewersPage(String projectKey, String slug) {
        super(projectKey, slug);
    }

    public AddRuleDialog addRule() {
        if (isShowingOnboarding().byDefaultTimeout()) {
            addButtonEmptyState.click();
        } else {
            addButton.click();
        }
        return pageBinder.bind(AddRuleDialog.class, this);
    }

    public DefaultReviewersPage deleteAllRows() {
        elementFinder.findAll(By.className("delete-button")).forEach(deleteButton -> {
            deleteButton.select();
            elementFinder.find(By.className("delete-confirm-button")).click();
            PageElement confirmDialog = elementFinder.find(By.className("aui-message-success"));
            confirmDialog.find(By.className("icon-close")).click();
            Poller.waitUntilFalse(confirmDialog.timed().isVisible());
        });
        return this;
    }

    public List<DefaultReviewerRuleRow> getRows() {
        // In the UI, each "row" is actually a tbody element
        if (!ruleTable.timed().isVisible().byDefaultTimeout()) {
            return Collections.emptyList();
        }
        return ruleTable.findAll(By.cssSelector("tbody > tr"))
                .stream()
                .map(bind(pageBinder, DefaultReviewerRuleRow.class, this))
                .collect(toList());
    }

    @Override
    public String getUrl() {
        return String.format("/plugins/servlet/default-reviewers/projects/%s/repos/%s", projectKey, slug);
    }

    public TimedCondition isShowingOnboarding() {
        return firstContactScreen.timed().isVisible();
    }
}
