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

import com.atlassian.pageobjects.elements.ElementBy;
import com.atlassian.pageobjects.elements.PageElement;
import com.atlassian.webdriver.bitbucket.element.LocaleSelector;
import com.atlassian.webdriver.bitbucket.element.TimeZoneSelector;
import com.atlassian.webdriver.bitbucket.page.BitbucketPage;
import org.openqa.selenium.By;

import java.util.Collection;

public class ServerSettingsPage extends BitbucketPage {

    @ElementBy(className = "stash-server-settings-form")
    private PageElement parentForm;
    @ElementBy(id = "appTitle")
    private PageElement applicationTitle;
    @ElementBy(id = "baseUrl")
    private PageElement baseUrl;
    @ElementBy(id = "submit")
    private PageElement saveButton;
    @ElementBy(id = "cancel")
    private PageElement cancelLink;

    @Override
    public String getUrl() {
        return "/admin/server-settings";
    }

    public ServerSettingsPage setApplicationTitle(String applicationTitle) {
        this.applicationTitle.clear().type(applicationTitle);
        return this;
    }

    public ServerSettingsPage setBaseUrl(String baseUrl) {
        this.baseUrl.clear().type(baseUrl);
        return this;
    }

    public String getApplicationTitle() {
        return applicationTitle.getValue();
    }

    public String getBaseUrl() {
        return baseUrl.getValue();
    }

    public GitLfsAdminFormFragment getGitLfsFormFragment() {
        return pageBinder.bind(GitLfsAdminFormFragment.class, this);
    }

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

    public TimeZoneSelector getTimeZoneSelector() {
        return pageBinder.bind(TimeZoneSelector.class, elementFinder.find(By.id(TimeZoneSelector.ID)));
    }

    public SshAdminFormFragment getSshFormFragment() {
        return pageBinder.bind(SshAdminFormFragment.class, this);
    }

    public ServerSettingsPage clickSave() {
        waitForPageLoad((Runnable) () -> saveButton.click());
        return pageBinder.bind(ServerSettingsPage.class);
    }

    public AdminHomePage clickCancel() {
        cancelLink.click();
        return pageBinder.bind(AdminHomePage.class);
    }

    public Collection<String> getFieldsWithErrors() {
        return getFieldsWithErrors(parentForm);
    }
}

