import java.util.ArrayList;

/**
 * Derived class that represents an if statement in the SILLY language.
 *   @author Dave Reed
 *   @version 2/8/12
 */
public class If extends Statement {
    private Expression expr;
    private ArrayList<Statement> stmts;  
    /**
     * Reads in an if statement from the specified stream
     *   @param input the stream to be read from
     */
	public If(TokenStream input) throws Exception {
        Token keyword = input.next();
        if (!keyword.toString().equals("if")) {
	        throw new Exception("SYNTAX ERROR: Malformed if statement");
	    }

	    this.expr = new Expression(input);
        this.stmts = new ArrayList<Statement>();
        
        while (!input.lookAhead().toString().equals("end")) {
            this.stmts.add(Statement.getStatement(input));
        } 
        keyword = input.next();   
	}
    
    /**
	 * Executes the current if statement.
	 *   @param bindings the current variable bindings
	 */
	public void execute(Bindings bindings) throws Exception {
	    if (this.expr.evaluate(bindings).toBoolean()) {
	        for (Statement stmt : this.stmts) {
	            stmt.execute(bindings);
	        }
	    }
	}
    
	/**
	 * 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 " + this.expr + "\n";
        for (Statement stmt : this.stmts) {
            str += "    " + stmt + "\n";
        }
        return str + "end";
    }
}
