package org.fountainmc.api.command;

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

public class CommandManager {

    private final List<CommandHandler> commands;

    public CommandManager() {
        this.commands = new ArrayList<CommandHandler>();
    }

    public void registerCommands(Object source) {
        for (Method method : source.getClass().getDeclaredMethods()) {
            if (Modifier.isPublic(method.getModifiers())) {
                if (method.isAnnotationPresent(Command.class)) {
                    Command command = method.getAnnotation(Command.class);
                    commands.add(new CommandHandler(command, method, source));
                }
            }
        }
    }

    public void fireCommand(String command, String[] arguments, CommandSender sender) {
        for (CommandHandler handler : commands) {
            if (handler.command.name().equalsIgnoreCase(command)) {
                Class<? extends CommandSender> senderClass = handler.command.allow();
                if (senderClass.isAssignableFrom(sender.getClass())) {
                    try {
                        handler.method.invoke(handler.source, arguments, senderClass.cast(sender));
                    }
                    catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    public List<CommandHandler> getCommands() {
        return commands;
    }

    public class CommandHandler {

        private final Command command;
        private final Method method;
        private final Object source;

        private CommandHandler(Command command, Method method, Object source) {
            this.command = command;
            this.method = method;
            this.source = source;
        }

        public Command getCommand() {
            return command;
        }

        public Method getMethod() {
            return method;
        }

        public Object getSource() {
            return source;
        }
    }

}

@@ -1032,32 +1032,208 @@
 and)) %7B%0A        
+        fireCommand(handler, arguments, sender);%0A            %7D%0A        %7D%0A    %7D%0A%0A    public void fireCommand(CommandHandler handler, String%5B%5D arguments, CommandSender sender) %7B%0A
         Class%3C? 
@@ -1298,32 +1298,24 @@
 ();%0A        
-      
-  
 if (senderCl
@@ -1373,28 +1373,14 @@
     
-        try %7B%0A      
+try %7B%0A
     
@@ -1391,18 +1391,16 @@
         
-  
 handler.
@@ -1479,33 +1479,18 @@
         
-        %7D%0A       
+%7D%0A
         
@@ -1493,17 +1493,16 @@
         
- 
 catch (I
@@ -1599,24 +1599,16 @@
         
-        
 e.printS
@@ -1624,48 +1624,8 @@
 ();%0A
-                    %7D%0A                %7D%0A
     

Move CommandHandler firing to a separate method