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

import com.atlassian.pageobjects.binder.WaitUntil;
import com.atlassian.pageobjects.elements.ElementBy;
import com.atlassian.pageobjects.elements.PageElement;
import com.atlassian.pageobjects.elements.query.Poller;
import com.atlassian.webdriver.bitbucket.element.LocaleSelector;
import com.atlassian.webdriver.bitbucket.page.admin.AbstractDatabasePage;
import org.openqa.selenium.By;

public class SetupDatabasePage extends AbstractDatabasePage<SetupDatabasePage> implements SetupTrackingPage {

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

    @ElementBy(id = "submit")
    private PageElement nextButton;

    @ElementBy(id = "internal-false")
    private PageElement externalRadioButton;

    @ElementBy(id = "internal-true")
    private PageElement internalRadioButton;

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

    private String getStepHeading() {
        return "Welcome";
    }

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

    public LocaleSelector getLocale() {
        return new LocaleSelector(body);
    }

    public SetupSettingsPage clickNext() {
        nextButton.click();
        return pageBinder.bind(SetupSettingsPage.class);
    }

    public SetupDatabasePage clickExternal() {
        externalRadioButton.click();
        Poller.waitUntilTrue(elementFinder.find(By.className("config-fields")).timed().isVisible());
        return this;
    }

    public SetupDatabasePage clickInternal() {
        internalRadioButton.click();
        return this;
    }

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

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

}
