package com.atlassian.webdriver.bitbucket.page.setup;

import com.atlassian.pageobjects.binder.PageBindingWaitException;
import com.atlassian.pageobjects.binder.WaitUntil;
import com.atlassian.pageobjects.elements.ElementBy;
import com.atlassian.pageobjects.elements.PageElement;
import com.atlassian.pageobjects.elements.PageElementFinder;
import com.atlassian.pageobjects.elements.query.Poller;
import com.atlassian.webdriver.bitbucket.page.BitbucketPage;
import org.openqa.selenium.By;

public abstract class SetupPage extends BitbucketPage implements SetupTrackingPage {

    @ElementBy(id = "setup-progress-iframe")
    private PageElement setupProgressTrackingIframe;

    @WaitUntil
    public void ensureHeadingMatches() {
        isOnSetupStep(this, elementFinder, getStepHeading());
    }

    public abstract String getStepHeading();

    public String getTrackingIframeTargetUrl() {
        return setupProgressTrackingIframe.getAttribute("src");
    }

    @Override
    public String getUrl() {
        return "/setup";
    }

    public boolean hasTrackingIframe() {
        return setupProgressTrackingIframe.isPresent();
    }

    static void isOnSetupStep(BitbucketPage page, PageElementFinder elementFinder, String title) {
        PageElement headingElement = elementFinder.find(By.cssSelector(".step .setup-header h2"));
        try {
            Poller.waitUntilTrue(headingElement.timed().hasText(title));
        } catch (AssertionError e) {
            if (headingElement.isPresent() && headingElement.isVisible()) {
                throw new PageBindingWaitException(String.format("Expected heading to be %s, got %s", title, headingElement.getText().trim()), page);
            } else {
                throw new PageBindingWaitException("Failed to find heading on SetupPage", page);
            }
        }
    }
}
