tcr/java/src/game/command/EnumParser.java

51 lines
1.2 KiB
Java
Raw Normal View History

2025-03-11 00:23:54 +01:00
package game.command;
import java.util.Map;
2025-03-16 17:40:47 +01:00
import com.google.common.collect.Maps;
2025-03-11 00:23:54 +01:00
2025-03-19 21:54:09 +01:00
public class EnumParser<T> extends DefaultingParser {
private final Class<T> clazz;
private final Map<String, T> lookup = Maps.newHashMap();
private final T[] selections;
2025-03-11 00:23:54 +01:00
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();
}
2025-03-19 21:54:09 +01:00
public EnumParser(String name, Class<T> clazz, T def, T ... selections) {
2025-03-11 00:23:54 +01:00
super(name, def, selections);
2025-03-19 21:54:09 +01:00
this.clazz = clazz;
2025-03-11 00:23:54 +01:00
this.selections = selections;
2025-03-19 21:54:09 +01:00
for(T o : selections) {
2025-03-11 00:23:54 +01:00
this.lookup.put(o.toString().toLowerCase(), o);
}
}
2025-03-19 21:54:09 +01:00
public T parse(ScriptEnvironment env, String input) {
T value = this.lookup.get(input.toLowerCase());
2025-03-11 00:23:54 +01:00
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];
}
2025-03-19 21:54:09 +01:00
public Class<?> getTypeClass() {
return this.clazz;
}
2025-03-11 00:23:54 +01:00
}