package com.atlassian.webdriver.bitbucket.element;

import com.atlassian.bitbucket.test.BuildStatusTestHelper;
import com.atlassian.pageobjects.elements.PageElement;
import com.atlassian.pageobjects.elements.WebDriverLocatable;
import com.atlassian.pageobjects.elements.query.Poller;
import com.atlassian.pageobjects.elements.timeout.TimeoutType;
import com.google.common.base.Function;
import com.google.common.collect.Lists;
import org.openqa.selenium.By;

import java.util.List;

public class BuildStatusDialog extends Dialog {

    public BuildStatusDialog(By locator) {
        super(locator);
    }

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

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

    public List<BuildStatusLine> getBuildStatusLines() {
        PageElement buildStatusList = find(By.className("build-status-list"));
        Poller.waitUntilTrue(buildStatusList.timed().isVisible());
        return Lists.newArrayList(Lists.transform(buildStatusList.findAll(By.tagName("li")),
                element -> pageBinder.bind(BuildStatusLine.class, element)
        ));
    }

    public static class BuildStatusLine {

        private final PageElement element;

        public BuildStatusLine(PageElement element) {
            this.element = element;
        }

        public BuildStatusTestHelper.State getStatus() {
            PageElement icon = element.find(By.className("build-icon"));
            if (!icon.isPresent()) {
                return null;
            }
            if (icon.hasClass("successful-build-icon")) {
                return BuildStatusTestHelper.State.SUCCESSFUL;
            }
            if (icon.hasClass("failed-build-icon")) {
                return BuildStatusTestHelper.State.FAILED;
            }
            if (icon.hasClass("inprogress-build-icon")) {
                return BuildStatusTestHelper.State.INPROGRESS;
            }
            return null;
        }

    }
}
