package visiteur;

import java.util.Map;

@Exercice(5)
public class EvalVisitor extends AbstractVisitor {

	private Map<Character, Double> map=null;
	private double value;

	public EvalVisitor(){}
	
	public double getValue() {
		return value;
	}

	public EvalVisitor(Map<Character, Double> map){
		this.map = map;
	}
	
	private double doVisit(BinaryOp e) {
		e.getRChild().accept(this);
		double x=value;
		e.getLChild().accept(this);
		return x;
	}

	public void visit(Addition e) {
		double x=doVisit(e);
		value+=x;
	}
	
	public void visit(Substraction e) {
		double x=doVisit(e);
		value-=x;
	}
	
	public void visit(Multiplication e) {
		double x=doVisit(e);
		value*=x;
	}

	public void visit(Division e) {
		double x=doVisit(e);
		value/=x;
	}

	public void visit(Value e) {
			value=e.getValue();
	}

	public void visit(Variable e) {
		if(map == null) throw new UnassignedVariableException(""+e.getValue());
		Double d = map.get(e.getValue());
		if(d == null) throw new UnassignedVariableException(""+e.getValue());
		value = d;
	}

}
