package game.console;
import game.console.command.ExitCommand;
import game.console.command.PhysicsCommand;
import game.console.command.PrintCommand;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Console {
private Map<String, Command> commands;
public Console() {
commands = new HashMap<String, Command>();
// Default commands
addCommand("exit", new ExitCommand());
addCommand("print", new PrintCommand());
addCommand("phys", new PhysicsCommand());
}
public void addCommand(String commandName, Command commandAction) {
commands.put(commandName, commandAction);
}
public void executeCommand(String commandString) {
System.out.println(">>> " + commandString);
String[] split = commandString.split("\\s+", 2);
String commandName = split[0];
Command command = commands.get(commandName);
if (command != null) {
String[] args;
if (split.length == 2) {
args = split(split[1]);
} else {
args = new String[0];
}
command.execute(args);
} else {
System.out.println("Unknown command!");
}
}
public void executeStream(InputStream commands) {
InputStreamReader isr = new InputStreamReader(commands);
BufferedReader reader = new BufferedReader(isr);
try {
String command = reader.readLine();
while (command != null) {
executeCommand(command);
command = reader.readLine();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static String[] split(String string) {
List<String> matchList = new ArrayList<String>();
Pattern regex = Pattern.compile("[^\\s\"']+|\"([^\"]*)\"|'([^']*)'");
Matcher regexMatcher = regex.matcher(string);
while (regexMatcher.find()) {
if (regexMatcher.group(1) != null) {
// Add double-quoted string without the quotes
matchList.add(regexMatcher.group(1));
} else if (regexMatcher.group(2) != null) {
// Add single-quoted string without the quotes
matchList.add(regexMatcher.group(2));
} else {
// Add unquoted word
matchList.add(regexMatcher.group());
}
}
String[] result = new String[matchList.size()];
return matchList.toArray(result);
}
}