package cz.moneta.test.harness.endpoints.ufo;

import cz.moneta.test.harness.context.StoreAccessor;
import cz.moneta.test.harness.data.Browser;
import cz.moneta.test.harness.endpoints.WebEndpoint;
import cz.moneta.test.harness.exception.FailElementDisplayedException;
import cz.moneta.test.harness.support.util.Level;
import cz.moneta.test.harness.support.web.Lookup;
import cz.moneta.test.harness.support.web.Until;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.openqa.selenium.By;

import java.util.concurrent.TimeUnit;

public class UfoEndpoint extends WebEndpoint {

    private static final String ENDPOINT_URL_IDENTIFIER = "endpoints.ufo.banka.url";
    private static final Browser DEFAULT_BROWSER = Browser.MS_EDGE;
    private static final String XPATH_TO_FAIL = "//*[@id='ERR405_S001'] " +
            "| //*[@id='ERR405_S002'] " +
            "| //*[@id='ERR405_S003'] " +
            "| //*[@id='ERR005_S001'] " +
            "| //*[@id='ERR005_S002'] " +
            "| //*[@id='ERR005_S003'] " +
            "| //*[@id='ERR004_S001']";
    private static final String ERROR_DETAIL_XPATH = "//textarea[contains(@title, 'Detail chyby')]";
    private static final String SESSION_ID_XPATH = "//input[@name = 'sessionId']";

    private static final Logger logger = LogManager.getLogger(UfoEndpoint.class);

    public UfoEndpoint(StoreAccessor storeAccessor) {
        super(ENDPOINT_URL_IDENTIFIER, By::id, storeAccessor, DEFAULT_BROWSER);
        setImplicitlyWait();
    }

    public UfoEndpoint(StoreAccessor storeAccessor, String token) {
        super(ENDPOINT_URL_IDENTIFIER, By::id, storeAccessor, DEFAULT_BROWSER);
        storeAccessor.log(Level.INFO, "UfoEndpoint with token {}", token);
        setImplicitlyWait();
    }

    private void setImplicitlyWait() {
        this.connector
                .get()
                .getDriver()
                .manage()
                .timeouts()
                .implicitlyWait(0L, TimeUnit.MILLISECONDS);
    }

    @Override
    public void waitForElementsToLoad(int timeoutSeconds, Lookup lookup, Until until, String... elementsToCheck) {
        try {
            super.waitOrFailOnErrorXpath(timeoutSeconds, lookup, until, XPATH_TO_FAIL, elementsToCheck);
        } catch (FailElementDisplayedException failElementException) {
            String errorDetail = getAttribute(ERROR_DETAIL_XPATH, Lookup.XPATH, "value");
            String ufoSessionId = getAttribute(SESSION_ID_XPATH, Lookup.XPATH, "value");
            String exceptionText = "Error page displayed (UFO Session ID: " + ufoSessionId + ") with following detail: " + errorDetail;
            logger.error(exceptionText);
            throw new FailElementDisplayedException(exceptionText, failElementException);
        }
    }
}