50 lines
1.2 KiB
Java
50 lines
1.2 KiB
Java
package game.command;
|
|
|
|
import java.util.Map;
|
|
|
|
import com.google.common.collect.Maps;
|
|
|
|
public class EnumParser<T> extends DefaultingParser {
|
|
private final Class<T> clazz;
|
|
private final Map<String, T> lookup = Maps.newHashMap();
|
|
private final T[] selections;
|
|
|
|
private static <T> String joinArgs(T[] iter) {
|
|
StringBuilder sb = new StringBuilder("'");
|
|
for(T obj : iter) {
|
|
if(sb.length() > 1)
|
|
sb.append("', '");
|
|
sb.append(String.valueOf(obj));
|
|
}
|
|
return sb.append("'").toString();
|
|
}
|
|
|
|
public EnumParser(String name, Class<T> clazz, T def, T ... selections) {
|
|
super(name, def, selections);
|
|
this.clazz = clazz;
|
|
this.selections = selections;
|
|
for(T o : selections) {
|
|
this.lookup.put(o.toString().toLowerCase(), o);
|
|
}
|
|
}
|
|
|
|
public T parse(ScriptEnvironment env, String input) {
|
|
T value = this.lookup.get(input.toLowerCase());
|
|
if(value != null)
|
|
return value;
|
|
int id = -1;
|
|
try {
|
|
id = Integer.parseInt(input);
|
|
}
|
|
catch(NumberFormatException e) {
|
|
}
|
|
if(id < 0 || id >= this.selections.length)
|
|
throw new ScriptException("Ungültige Auswahl '%s', muss eine von diesen Optionen sein: %s", input,
|
|
joinArgs(this.selections));
|
|
return this.selections[id];
|
|
}
|
|
|
|
public Class<?> getTypeClass() {
|
|
return this.clazz;
|
|
}
|
|
}
|