/*
 *	Modulname:	Page
 *	Autor:		Eyer Leander
 *	Datum:		11.05.2006
 *
 *	(c) Copyright 2005
 */
package survey.model;

import java.util.Iterator;
import java.util.Vector;

/**
 * A page in the survey. It contains a set of questions
 */
public class Page implements QuestionListener {

	/** The label of the page */
	private String label = "";

	/** Questions displayed on this page */
	private Vector<SurveyElement> pageElements = new Vector<SurveyElement>();

	/** Vector containing only the questions */
	private Vector<Question> questions = new Vector<Question>();

	/** List of Question Listeners */
	private Vector<QuestionListener> listeners = new Vector<QuestionListener>();

	/**
	 * Constructor
	 */
    public Page() {}


	/**
	 * Add a question to this page
	 * @param question 	Question to be added
	 */
	public void addQuestion(Question question) {
		pageElements.add(question);
		questions.add(question);
		question.addListener(this);
	}

	/** Add a label to the page */
	public void addLabel(Label label) {
		pageElements.add(label);
	}

	/**
	 * @return an iterator over all questions on this page
	 */
	public Iterator<SurveyElement> getPageElements() {
		return pageElements.iterator();
	}

	/**
	 * @return an iterator over all questions on this page
	 */
	public Iterator<Question> getQuestions() {
		return questions.iterator();
	}

	/**
	 * Check if all mandatory questions have been answered
	 * @return	true if the user can go to the next page
	 */
	public boolean areAllMandatoryAnswered() {
		for (Question q:questions) {
			if (q.isMandatory() && (q.hasBeenAnswered() == false)) {
				return false;
			}
		}
		return true;
	}

	/** @return the label of this page */
	public String getLabel() {
		return label;
	}

	/** Change the label of this text */
	public void setLabel(String label) {
		this.label = label;
	}

	/** Add a listener of changes of state in questions */
	public void addListener(QuestionListener listener) {
		listeners.add(listener);
	}

	/** Remove a listener of changes of states in questions */
	public void removeListener(QuestionListener listener) {
		listeners.remove(listener);
	}

	/**
	 * Inform all listeners about a change of state in a question
 	 * @param question	Question whose state changed
	 */
	private void fireQuestionStateChangedEvent(Question question) {
		for (QuestionListener listener:listeners) {
			listener.questionStateChanged(question);
		}
	}

	/**
	 * 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) {
		fireQuestionStateChangedEvent(question);
	}
}

