package com.xebia.incubator.xebium.fastseleniumemulation;

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.internal.seleniumemulation.AlertOverride;
import org.openqa.selenium.internal.seleniumemulation.SeleneseCommand;

public class Type extends SeleneseCommand<Void> {
	private final AlertOverride alertOverride;
	private final ElementFinder finder;

	public Type(AlertOverride alertOverride, ElementFinder finder) {
		this.alertOverride = alertOverride;
		this.finder = finder;
	}

	@Override
	protected Void handleSeleneseCommand(WebDriver driver, String locator, String value) {
		alertOverride.replaceAlertMethod(driver);

		value = value.replace("\\10", Keys.ENTER);
		value = value.replace("\\13", Keys.RETURN);
		value = value.replace("\\27", Keys.ESCAPE);
		value = value.replace("\\38", Keys.ARROW_UP);
		value = value.replace("\\40", Keys.ARROW_DOWN);
		value = value.replace("\\37", Keys.ARROW_LEFT);
		value = value.replace("\\39", Keys.ARROW_RIGHT);

		WebElement element = finder.findElement(driver, locator);

		clear(element);
		element.sendKeys(value);
		triggerEvents(driver);

		return null;
	}

	// Make sure onchange/onblur are triggered
	private void triggerEvents(WebDriver driver) {
		driver.findElement(By.tagName("body")).click();
	}

	private void clear(WebElement element) {
		if (isInput(element) && element.isEnabled()) {
			element.clear();
		}
	}

	private boolean isInput(WebElement element) {
		String tagName = element.getTagName();
		return "input".equalsIgnoreCase(tagName) || "textarea".equalsIgnoreCase(tagName);
	}
}

@@ -742,16 +742,58 @@
 iver);%0A%0A
+%09%09if (value == null) %7B%0A%09%09%09value = %22%22;%0A%09%09%7D%0A
 %09%09value 
@@ -1243,16 +1243,25 @@
 rEvents(
+element, 
 driver);
@@ -1360,117 +1360,41 @@
 (Web
-Driver driver) %7B%0A%09%09driver.findElement(By.tagName(%22body%22)).click();%0A%09%7D%0A%0A%09private void clear(WebElement element
+Element element, WebDriver driver
 ) %7B%0A
@@ -1403,67 +1403,105 @@
 if (
+%22
 i
-sI
 nput
-(element) && element.isEnabled()) %7B%0A%09%09%09element.clear
+%22.equalsIgnoreCase(element.getTagName())) %7B%0A%09%09%09driver.findElement(By.tagName(%22body%22)).click
 ();%0A
@@ -1521,23 +1521,18 @@
 ate 
-boolean isInput
+void clear
 (Web
@@ -1593,23 +1593,21 @@
 me();%0A%09%09
-return 
+if ((
 %22input%22.
@@ -1671,15 +1671,66 @@
 tagName)
+) && element.isEnabled()) %7B%0A%09%09%09element.clear()
 ;%0A
+%09
 %09%7D%0A
+%09%7D%0A%0A
 %7D%0A

Allow empty value for Type