package dkohl.bayes.probability.distribution.tree;

import java.util.HashMap;
import java.util.LinkedList;

import dkohl.bayes.probability.Assignment;
import dkohl.bayes.probability.Probability;
import dkohl.bayes.probability.distribution.ProbabilityDistribution;

/**
 * Represents a random variable. Maps each outcome to a successor.
 * 
 * @author Daniel Kohlsdorf
 */
public class DecisionNode implements ProbabilityDistribution {

	/**
	 * The successors for each outcome
	 */
	private HashMap<String, ProbabilityDistribution> successors;

	/**
	 * Name of the variable
	 */
	private String variable;

	public DecisionNode(String variable) {
		this.variable = variable;
		successors = new HashMap<String, ProbabilityDistribution>();
	}

	public String getVariable() {
		return variable;
	}

	public void put(String value, ProbabilityDistribution distribution) {
		successors.put(value, distribution);
	}

	public HashMap<String, ProbabilityDistribution> getSuccessors() {
		return successors;
	}

	@Override
	public Probability eval(LinkedList<Assignment> assignment) {
		// Evaluate recursively
		for (Assignment a : assignment) {
			if (a.getVariable().getName().equals(variable)) {
				return successors.get(a.getValue()).eval(assignment);
			}
		}

		try {
			throw (new Exception("Domain Violation: " + variable));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

}
