package cz.moneta.test.dsl.ufo;

import cz.moneta.test.dsl.Harness;
import cz.moneta.test.dsl.ufo.common.authentication.UfoLoginPage;
import cz.moneta.test.dsl.ufo.common.landing.ADM162_S001_selectPageTomcatSso;
import cz.moneta.test.harness.endpoints.ufo.UfoEndpoint;
import cz.moneta.test.harness.support.web.Builders;
import cz.moneta.test.harness.support.web.Lookup;
import cz.moneta.test.harness.support.web.Until;

public class Ufo {

    private final Harness harness;
    private Object[] args;

    public Ufo(Harness harness, Object... args) {
        this.harness = harness;
        this.args = args;
    }

    public UfoLoginPage openLoginPage() {
        UfoEndpoint endpoint = harness.getEndpoint(UfoEndpoint.class, args);
        endpoint.openApplication();
        checkServerError500(endpoint);
        logSessionId(endpoint);
        return Builders.newWebFlowBuilder(UfoLoginPage.class, endpoint, harness);
    }

    /**
     * FOR LOCAL USE ONLY!!! DON'T USE IT ON JENKINS!!!
     * For correct work, parameter endpoints.ufo.banka.url in resources/envs/ must be changed
     *
     * TODO: make it work on Jenkins
     */
    public ADM162_S001_selectPageTomcatSso openLoginPageTomcat() {
        UfoEndpoint endpoint = harness.getEndpoint(UfoEndpoint.class, args);
        endpoint.openApplication();
        checkServerError500(endpoint);
        logSessionId(endpoint);
        return Builders.newWebFlowBuilder(ADM162_S001_selectPageTomcatSso.class, endpoint, harness);
    }

    private void logSessionId(UfoEndpoint endpoint) {
        String ufoSessionId = endpoint.getAttribute("//input[@name = 'sessionId']", Lookup.XPATH, "value");
        harness.log("UFO Session ID: " + ufoSessionId);
        harness.store("reports.tmfj.execution.commentufosessionid", ufoSessionId);
    }

    private void checkServerError500(UfoEndpoint endpoint) {
        endpoint.waitOrFailOnErrorXpath(1, Lookup.XPATH, Until.PRESENT_IN_DOM, "//*[@id='http500']");
    }

    public void closeApplication() {
        harness.closeEndpoint(harness.getEndpoint(UfoEndpoint.class, args));
    }
}
