package com.leandog.gametel.driver.commands;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import com.jayway.android.robotium.solo.Solo;
import com.leandog.gametel.driver.TestRunInformation;

public class CommandRunner {

    private Object theLastResult;

    public void execute(final Command command) {
        try {
            final Method method = finaMethodFor(command);
            theLastResult = method.invoke(TestRunInformation.getSolo(), command.getArguments());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private Method finaMethodFor(final Command command) throws NoSuchMethodException {
        List<Class<?>> types = new ArrayList<Class<?>>();
        for(final Object argument : command.getArguments()) {
            Class<? extends Object> argumentType = argument.getClass();
            if( argumentType.equals(Integer.class) ) {
                argumentType = int.class;
            }
            types.add(argumentType);
        }
        
        Class<?>[] typesArray = new Class<?>[types.size()];
        types.toArray(typesArray);
        return Solo.class.getMethod(command.getName(), typesArray);
    }

    public Object theLastResult() {
        return theLastResult;
    }

}

@@ -75,59 +75,8 @@
 hod;
-%0Aimport java.util.ArrayList;%0Aimport java.util.List;
 %0A%0Aim
@@ -335,25 +335,25 @@
 method = fin
-a
+d
 MethodFor(co
@@ -545,24 +545,97 @@
    %7D%0A    %7D%0A%0A
+    public Object theLastResult() %7B%0A        return theLastResult;%0A    %7D%0A%0A
     private 
@@ -644,17 +644,17 @@
 thod fin
-a
+d
 MethodFo
@@ -721,124 +721,168 @@
     
-List%3CClass%3C?%3E%3E types = new ArrayList%3CClass%3C?%3E%3E();%0A        for(final Object argument : command.getArguments()) %7B%0A    
+%0A        return Solo.class.getMethod(command.getName(), argumentTypesFor(command));%0A    %7D%0A%0A    private Class%3C? extends Object%3E typeFor(final Object argument) %7B%0A
     
@@ -953,20 +953,16 @@
         
- 
-   
 if( argu
@@ -1008,20 +1008,16 @@
         
-    
 argument
@@ -1038,28 +1038,24 @@
 ss;%0A        
-  
-  
 %7D%0A          
@@ -1056,22 +1056,15 @@
     
-    types.add(
+return 
 argu
@@ -1075,29 +1075,85 @@
 Type
-)
 ;%0A    
+%7D%0A
     
-%7D
 %0A    
-    
+private Class%3C?%3E%5B%5D argumentTypesFor(final Command command) %7B
 %0A   
@@ -1173,21 +1173,16 @@
 %5B%5D types
-Array
  = new C
@@ -1193,168 +1193,200 @@
 %3C?%3E%5B
-types.size()%5D;%0A        types.toArray(typesArray);%0A        return Solo.class.getMethod(command.getName(), typesArray);%0A
+command.getArguments().length%5D;%0A        %0A        int index = 0;%0A        for(final Object argument : command.getArguments()) %7B%0A            types%5Bindex++%5D = typeFor(argument);%0A    
     %7D%0A
-%0A
     
-public Object theLastResult() %7B
+    
 %0A   
@@ -1394,35 +1394,27 @@
     return t
-heLastResult
+ypes
 ;%0A    %7D%0A%0A%7D%0A

refactor for int primitive