package cz.moneta.test.harness.connectors.web;

import cz.moneta.test.harness.support.web.Lookup;
import cz.moneta.test.harness.support.web.TextContainer;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;

import java.util.Optional;

public class Types {

    private final SeleniumWebConnector connector;

    public Types(SeleniumWebConnector connector) {
        this.connector = connector;
    }

    public void type(TextContainer input, String text, boolean clear, Lookup lookup) {
        if (clear) {
            clearInput(input, lookup);
        }
        connector.waits()
                .waitForLazyElement(input.getPath(), lookup)
                .sendKeys(text);
    }

    public void jsType(TextContainer input, String text, boolean clear, Lookup lookup) {
        if (clear) {
            clearInput(input, lookup);
        }
        Optional.of(connector.getDriver())
                .filter(JavascriptExecutor.class::isInstance)
                .map(JavascriptExecutor.class::cast)
                .ifPresent(e -> {
                    WebElement element = connector.waits().waitForLazyElement(input.getPath(), lookup);
                    if ("textarea".equals(element.getTagName())) {
                        e.executeScript("arguments[0].value=arguments[1];", element, text);
                    } else {
                        e.executeScript("arguments[0].setAttribute('value', arguments[1]);", element, text);
                    }
                });
    }

    private void clearInput(TextContainer input, Lookup lookup) {
        connector.waits()
                .waitForLazyElement(input.getPath(), lookup)
                .sendKeys(Keys.chord(Keys.CONTROL, "a"), Keys.BACK_SPACE);
    }

    public void typeWithControlDown(String input, String keys, Lookup lookup) {
        new Actions(connector.getDriver())
                .click(connector.waits().waitForLazyElement(input, lookup))
                .keyDown(Keys.CONTROL)
                .sendKeys(keys)
                .keyUp(Keys.CONTROL)
                .perform();
    }

}
