summaryrefslogtreecommitdiff
path: root/com/nemez/cmdmgr/util/ExecutableDefinition.java
blob: f04b65a1d22689f21ccb6873f4588626ac957d36 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package com.nemez.cmdmgr.util;

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

import org.bukkit.command.CommandSender;

import com.nemez.cmdmgr.component.ArgumentComponent;
import com.nemez.cmdmgr.component.ICommandComponent;

public class ExecutableDefinition {

	private ArrayList<ICommandComponent> components;
	private String permission;
	private Method target;
	private Object methodContainer;
	
	public ExecutableDefinition(ArrayList<ICommandComponent> cmd, String perm, Method method, Object methodContainer) {
		this.components = cmd;
		this.permission = perm;
		this.target = method;
		this.methodContainer = methodContainer;
	}
	
	public boolean valid(int index, String arg) {
		if (index < 0 || index >= components.size()) {
			return false;
		}
		return components.get(index).valid(arg);
	}

	public Object get(int index, String arg) {
		if (index < 0 || index >= components.size()) {
			return null;
		}
		return components.get(index).get(arg);
	}
	
	public boolean isArgument(int index) {
		if (index < 0 || index >= components.size()) {
			return false;
		}
		return components.get(index) instanceof ArgumentComponent;
	}
	
	public boolean isHelp() {
		return target == null && components.get(0).valid("help") && components.get(1).getComponentInfo().equals("<page:i32>");
	}
	
	public String getPermission() {
		return permission;
	}
	
	public int getLength() {
		return components.size();
	}
	
	public boolean invoke(ArrayList<Object> args, CommandSender sender) {
		if (target == null) {
			return false;
		}
		Object[] arguments = new Object[args.size() + 1];
		for (int i = 1; i < arguments.length; i++) {
			arguments[i] = args.get(i - 1);
		}
		arguments[0] = sender;
		try {
			if (target.getReturnType() == void.class) {
				target.invoke(methodContainer, arguments);
				return true;
			}else if (target.getReturnType() == boolean.class) {
				return (boolean) target.invoke(methodContainer, arguments);
			}
		} catch (Exception e) {
			System.err.println("M8 you're missing a function...");
			e.printStackTrace();
			return true;
		}
		return false;
	}
}