package Cluedo.GUI;
import java.util.Vector;
import java.util.StringTokenizer;

/**
 * Filters commands and returns the typed information in an array
 * or null if the data was invalid.<p>
 * 
 * Note:<br>
 * This is a <b>parser</b> and only a parser.. it does not "handle events". See TextEventHandler.
 *
 * @author Alex
 */
public class TextParser {
	  /**
	  * List of valid commands
	  */
	  Vector consoleCommands = new Vector();
	  /**
	   * File to load valid commands from.
	   */
	  String validCommands = "commands.default";
	  
	  int debugParser = 0;
	  
	  public TextParser() {
  	
	  	/**
	  	 *		Any command to be accepted by this parser must be registered below.
	  	 *
	  	 *
	  	 */
	  		loadCommands();


	  }

	  /**
	   * Loads from a resource file a list of commands.
	   *
	   */
	  public void loadCommands() {
	  	try {
	  		StringTokenizer lines = new StringTokenizer(
	  							Cluedo.API.Resources.catTextFile("commands.dat", this), "\n");
	  			while(lines.hasMoreTokens() == true) {
	  				consoleCommands.add(lines.nextToken());
	  				if(debugParser == 2)
	  					System.out.println("[TextParser:loadCommands] nextCommand: " + (consoleCommands.elementAt(consoleCommands.size()-1)) );
	  			}
	  	}
	  	catch (Exception general) {
	  		System.out.println("[TextParser:loadCommands] Can't load commands, fatal error.\n");
	  		System.exit(-1);
	  	}
	  }
	  
	  /**
	  * Checks whether a command is a valid console command (ie, memeber of the list of commands).
	  * 
	  * @param commandLine Command line
	  * @return null if the command is valid, else an array of tokens
	  */
	  public String[] parseCommandLine(String commandLine) {
	 	StringTokenizer tokens = new StringTokenizer(commandLine, " ");
	 	if(tokens.countTokens() == 0)
	 		return null;
	 	
		String parts[] = new String[tokens.countTokens()];
		if(debugParser == 1) 
			System.out.println("[SimpleParser:parseCommandLine] tokens " + tokens.countTokens());

		for(int i = 0; tokens.hasMoreTokens() == true; i++) {
			parts[i] = tokens.nextToken();
			if(debugParser > 1)
				System.out.println("[SimpleParser:parseCommandLine] part " + parts[i]);
		}

	 	if(consoleCommands.contains(parts[0]))
	 		return parts;	
	 	else
	 		return null;
	 }

	
}
