import java.util.ArrayList;

/**
 * Derived class that represents an if statement in the SILLY language.
 * 
 * @author Dave Reed
 * @version 2/9/07
 */
public class If extends Statement
{
    private Expression expr;
    private ArrayList<Statement> stmts;
    
    /**
     * Reads in an if statement from the specified program
     *   @param program the source code of the program to be read from
     */
	public void read(SourceCode program) {
        Token start = program.next();
        expr = new Expression();
        expr.read(program);
        
        stmts = new ArrayList<Statement>();
        while (!program.peek().toString().equals("end")) {
            stmts.add(Statement.getStatement(program));
        }
        Token end = program.next();
        
        if (!start.toString().equals("if") || !end.toString().equals("end")) {
	        System.out.println("SYNTAX ERROR: Malformed if statement");
	        System.exit(0);
	    }
	}
    
    /**
	 * Executes the current if statement.
	 *   @param variables the table representing the current bindings for all variables
	 */
	public void execute(VariableTable variables) {
	    if (expr.evaluate(variables) != 0) {
	        for (int i = 0; i < stmts.size(); i++) {
	            stmts.get(i).execute(variables);
	        }
	    }
	}
    
	/**
	 * Accesses the type of the current statement.
	 *   @return this statement's type, i.e., Statement.Type.IF
	 */
	public Statement.Type getType() {
	    return Statement.Type.IF;
	}
	
	/**
	 * Converts the current assignment statement into a String.
	 *   @return the String representation of this statement
	 */
    public String toString() {
        String str = "if " + expr + "\n";
        for (int i = 0; i < stmts.size(); i++) {
            str += "    " + stmts.get(i) + "\n";
        }
        return str + "end";
    }
}
