package io.appium.android.bootstrap.handler;

import io.appium.android.bootstrap.AndroidCommand;
import io.appium.android.bootstrap.AndroidCommandResult;
import io.appium.android.bootstrap.AndroidElement;
import io.appium.android.bootstrap.CommandHandler;
import io.appium.android.bootstrap.WDStatus;
import io.appium.android.bootstrap.exceptions.ElementNotInHashException;

import java.util.Hashtable;

import org.json.JSONException;

import com.android.uiautomator.core.UiObjectNotFoundException;

/**
 * This handler is used to set text in elements that support it.
 * 
 * @author <a href="https://github.com/xuru">xuru</a>
 * 
 */
public class SetText extends CommandHandler {

  /*
   * @param command The {@link AndroidCommand} used for this handler.
   * 
   * @return {@link AndroidCommandResult}
   * 
   * @throws JSONException
   * 
   * @see io.appium.android.bootstrap.CommandHandler#execute(io.appium.android.
   * bootstrap.AndroidCommand)
   */
  @Override
  public AndroidCommandResult execute(final AndroidCommand command)
      throws JSONException {
    if (command.isElementCommand()) {
      // Only makes sense on an element
      try {
        final Hashtable<String, Object> params = command.params();
        final AndroidElement el = command.getElement();
        final String text = params.get("text").toString();

        return getSuccessResult(el.setText(text));
      } catch (final UiObjectNotFoundException e) {
        return new AndroidCommandResult(WDStatus.NO_SUCH_ELEMENT,
            e.getMessage());
      } catch (final ElementNotInHashException e) {
        return new AndroidCommandResult(WDStatus.NO_SUCH_ELEMENT,
            e.getMessage());
      }
    } else {
      return getErrorResult("Unable to set text without an element.");
    }
  }
}

@@ -249,16 +249,59 @@
 andler;%0A
+import io.appium.android.bootstrap.Logger;%0A
 import i
@@ -468,24 +468,70 @@
 Exception;%0A%0A
+import com.android.uiautomator.core.UiDevice;%0A
 import com.a
@@ -1373,22 +1373,16 @@
         
-final 
 String t
@@ -1418,25 +1418,24 @@
 ring();%0A
-%0A
         
 return g
@@ -1430,32 +1430,246 @@
     
-return getSuccessR
+Boolean pressEnter = false;%0A        if (text.endsWith(%22%5C%5Cn%22)) %7B%0A          pressEnter = true;%0A          text = text.replace(%22%5C%5Cn%22, %22%22);%0A          Logger.info(%22Will press enter after setting text%22);%0A        %7D%0A        final Boolean r
 esult
-(
+ = 
 el.s
@@ -1680,16 +1680,171 @@
 xt(text)
+;%0A        if (pressEnter) %7B%0A          final UiDevice d = UiDevice.getInstance();%0A          d.pressEnter();%0A        %7D%0A        return getSuccessResult(result
 );%0A     

allow setText on android to press enter when it sees \n