/*

	Command.java
	by Richard Unger
	
	This object is used to store commands - in its basic form it contains
	just their string and the object responsible for executing them...
	
	It is also responsible for being able to invoke the owner object
	with the specific command and also to check whether specific strings
	match the general command this object represents...
	
*/


import java.util.StringTokenizer;



public class Command{

	public String commandFormat;
	CommandExecutor owner;
	
// constructor
	
	public Command(String text,CommandExecutor who){
		commandFormat = text;
		owner = who;
		}



// command related functions - this performs parsing right now, later this could be
// removed and implemented in a seperate parser object

	public String invoke(String commandInstance){
		return owner.performCommand(commandInstance);
		}
	
	public boolean matchesCommand(String test){
		return matches(test,commandFormat);
		}
	
	
	public String toString(){
		return commandFormat;
		}
	
// static... all commands match tokens the same way
	
	static public boolean matches(String test,String commandForm){
		StringTokenizer toke1 = new StringTokenizer(test,", ");
		StringTokenizer toke2 = new StringTokenizer(commandForm,", ");
		String tok1,tok2;
		
		if (toke1.countTokens()!=toke2.countTokens())
			return false;
		while (toke1.hasMoreTokens()){
			tok1 = toke1.nextToken();
			tok2 = toke2.nextToken();
			if (!matchesToken(tok1,tok2))
				return false;
			}
		return true;
		}
		
	static private boolean matchesToken(String t1,String t2){
		// t1 is token from actual command, t2 is token from grammar string

		if (t2.equals("<str>"))
			return true;
		if (t2.equals("<bool>")){
			if (t1.equals("true"))
				return true;
			if (t1.equals("false"))
				return true;
			return false;
			}
		if (t2.equals("<int>")){
			try {
				int x = Integer.parseInt(t1);
				}
			catch (NumberFormatException e){
				return false;
				}
			return true;
			}
		if (t2.equals("<dbl>")){
			try {
				Double d = new Double(t1);
				}
			catch (NumberFormatException e){
				return false;
				}
			return true;
			}
		if (t2.equals("<+->")){
			if (t1.equals("+") || t1.equals("-"))
				return true;
			else
				return false;
			}
		if (t2.equals(t1))
			return true;
		return false;
		}


}