package org.getopentest.selenium;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;

public class AssertElementText extends SeleniumTestAction {

    @Override
    public void run() {

        super.run();

        By locator = this.readLocatorArgument("locator");
        String text = this.readStringArgument("text", null);
        String textContains = this.readStringArgument("textContains", null);
        boolean caseInsensitive = this.readBooleanArgument("caseInsensitive", false);

        this.waitForAsyncCallsToFinish();

        WebElement element = this.getElement(locator);
        String elementText = element.getText();

        boolean textIsValid = false;

        if (text != null) {
            if (caseInsensitive) {
                textIsValid = elementText.equalsIgnoreCase(text);
            } else {
                textIsValid = elementText.equals(text);
            }

            if (!textIsValid) {
                throw new RuntimeException(String.format(
                        "Element %s failed validation. The expected value was \"%s\", "
                        + "but the actual value was \"%s\".",
                        locator, text, elementText));
            }
        } else if (textContains != null) {
            if (caseInsensitive) {
                textIsValid = elementText.toLowerCase().contains(textContains.toLowerCase());
            } else {
                textIsValid = elementText.contains(textContains);
            }

            if (!textIsValid) {
                throw new RuntimeException(String.format(
                        "Element %s failed validation. We expected its value to contain \"%s\", "
                        + "but the actual value was \"%s\".",
                        locator, textContains, elementText));
            }
        } else {
            throw new RuntimeException(
                    "Neither the \"text\" argument, nor the \"textContains\" "
                    + "argument were provided.");
        }

    }
}