import java.util.Stack;

/**
 * Class that models the stack partition of memory.
 *   @author Dave Reed
 *   @version 2/8/14
 */
public class MemoryStack {
	// Inner class for pairing a variable name and value in a single object.
	private class Pair {
		private Token token;
		private DataValue value;
		
		public Pair(Token t, DataValue v) {
			this.token = t;
			this.value = v;
		}
		
		public DataValue getValue() {
			return this.value;
		}
		
		public void setValue(DataValue v) {
			this.value = v;
		}
		
		public boolean equals(Object other) {
			return this.token.equals(((Pair)other).token);
		}
	}
	
	/////////////////////////////////
	
    private Stack<Pair> memStack;
    
    /**
     * Constructs an empty stack.
     */
    public MemoryStack() {
    	this.memStack = new Stack<Pair>();
    }
    /**
     * Stores a data value on the top of the memory stack.
     * @param variable the variable name the value is being stored under
     * @param val the data value (either an integer or a String)
     */
    public void store(Token variable, DataValue val) {
    	int index = this.memStack.indexOf(new Pair(variable, null));
    	if (index == -1) {
    		this.memStack.push(new Pair(variable, val));    	
    	}
    	else {
    	    this.memStack.get(index).setValue(val);
    	}
    }
    
    /**
     * Looks up the value associated with a variable in the stack.
     * @param variable the variable name being looked up
     * @return the data value for that variable (either an integer or a String)
     */
    public DataValue lookup(Token variable) throws Exception {
    	int index = this.memStack.indexOf(new Pair(variable, null));
    	if (index == -1) {
    		throw new Exception("UNITIALIZED VARIABLE: " + variable);
    	}
    	return this.memStack.get(index).getValue();
    }
}
