/*
 *	Modulname:	Dependencies
 *	Autor:		Eyer Leander
 *	Datum:		15.05.2006
 *
 *	(c) Copyright 2005
 */
package survey.model;

import java.util.Vector;


/**
 * This class is able to tell if a question should be active or not
 */
public class DependencyHandler implements QuestionListener {

	/** List of dependencies */
    private Vector<Dependency> dependencies = new Vector<Dependency>();
	/** Link to the model */
	private Model model;

	/** Area ll dependencies fullfilled */
	private boolean status = true;

	/** Listener for dependency changes */
	private Vector<DependencyListener> listeners = new Vector<DependencyListener>();

	/** Constructor */
	public DependencyHandler(Model model) {
		this.model = model;
	}

	/** Add a dependency */
	public void addDependency(String questionID, String expectedValue) {
		//the question whose state we check
		Question question = model.getQuestionByID(questionID);
		question.addListener(this);

		dependencies.add(new Dependency(question, expectedValue));
		calcFullfilled();
	}

	/** Recalculate the fullfilled state */
	private void calcFullfilled() {
		boolean cache = status;

		status = true;
		for (Dependency dep:dependencies) {
			if (dep.isFullfilled() == false) {
				status = false;
			}
		}

		if (status != cache) {
            fireDependencyChanged();
		}
	}

	/** Inform all listeners that the dependency status for this object has changed */
	private void fireDependencyChanged() {
		for (DependencyListener listener:listeners) {
			listener.dependencyChanged(status);
		}
	}

	public void addListener(DependencyListener listener) {
		listeners.add(listener);
	}

	public void removeListener(DependencyListener listener) {
		listeners.remove(listener);
	}

	/** Status of the dependencies */
	public boolean isFullfilled() {
		return status;
	}

	/**
	 * This method will be called when the state of a question is changed
	 * (i.e. the question becomes answered)
	 *
	 * @param question The question whose state changed
	 */
	public void questionStateChanged(Question question) {
        calcFullfilled();
	}
}

class Dependency {
	private Question question;
	private String expectedValue;

	public Dependency(Question question, String expectedValue) {
		this.question = question;
		this.expectedValue = expectedValue;
	}

	public boolean isFullfilled() {
		Object answer = question.getContentType().getAnswer();
		if ((answer != null) && (answer.toString().equals(expectedValue))) {
			return true;
		} else {
			return false;
		}
	}

}
