package cz.moneta.test.dsl.ufo.banka.pages.main;

import cz.moneta.test.harness.context.StoreAccessor;
import cz.moneta.test.harness.endpoints.ufo.UfoEndpoint;
import cz.moneta.test.harness.support.web.*;

import java.util.LinkedHashMap;

@Wait(value = PSP004_S001_PrintPage.PAGE_LABEL_XPATH, waitSecondsForElement = 120)
@Wait(explicitWaitSeconds = 5) //Error message: javascript error: window.parent.document.PSP004_S001_D002.done is not a function
public interface PSP004_S001_PrintPage extends WebFlow<PSP004_S001_PrintPage>, StoreAccessor {
    String PAGE_LABEL_XPATH = "PSP004_S001_D002";
    String DOCUMENT_URL_XPATH = "//*[@name='document_url']";
    String PRINT_DIV_FORM = "//div[@id='PSP004_S001']//parent::form";
    String MAIN_FORM = "//form[@action='%s']";
    String DOCUMENT_URLS_STORE_KEY = "PSP004_DOCUMENT_URLS";

    @CustomAction
    default PSP004_S001_PrintPageTransitions closePrintWindow() {
        UfoEndpoint endpoint = getEndpoint(UfoEndpoint.class);
        String actionId = endpoint.getAttribute(PRINT_DIV_FORM, Lookup.XPATH, "action");
        if (endpoint.isHeadlessModeOn()) {
            endpoint.executeScript("window.parent.document.PSP004_S001_D002.done()");
        } else {
            endpoint.executeScript("window.parent.dispatchEvent(new Event('focus'));");
        }
        endpoint.waitForElementsToLoad(30, Lookup.XPATH, Until.GONE, String.format(MAIN_FORM, actionId));
        return null;
    }

    @CustomAction
    default PSP004_S001_PrintPage saveDocumentUrl() {
        saveDocumentUrl(String.valueOf(System.currentTimeMillis()));
        return null;
    }

    @CustomAction
    default PSP004_S001_PrintPage saveDocumentUrl(String documentName) {
        UfoEndpoint endpoint = getEndpoint(UfoEndpoint.class);
        String url = endpoint.getAttribute(DOCUMENT_URL_XPATH, Lookup.XPATH, "value");

        LinkedHashMap<String, String> docUrlsMap = get(DOCUMENT_URLS_STORE_KEY, true);
        if (docUrlsMap == null) docUrlsMap = new LinkedHashMap<>();

        docUrlsMap.put(documentName, url);
        store(DOCUMENT_URLS_STORE_KEY, docUrlsMap);
        return null;
    }
}