/*
 *	Modulname:	RendererTextField
 *	Autor:		Eyer Leander
 *	Datum:		08.05.2006
 *
 *	(c) Copyright 2005
 */
package survey.gui;

import survey.model.Question;
import survey.model.TypeTextField;
import survey.Survey;

import javax.swing.*;
import java.awt.*;

/**
 * A renderer component for a question of type TextField
 */
public class RendererTextField extends Renderer implements TextChangeListener {

	// connection to the model
	private TypeTextField type;

	/** Label of the question */
	private JLabel questionLabel;

	// the textfield in which the user will provide the answer
	private ETextField txtAnswer;

	/** Constructor */
	public RendererTextField(Question element, TypeTextField type) {
		super(element);
		this.type = type;

		createUI();
		setEditable(getQuestion().isEditable());
	}

	/** Config the user interface */
	private void createUI() {
		setLayout(new BorderLayout(24, 24));

		String mandatoryFlag = getQuestion().isMandatory()? "* ":"";

		questionLabel = new JLabel("<html><body>" + mandatoryFlag + getQuestion().getLabel() + "</body></html>");
        questionLabel.setFont(Survey.FONT_QUESTION_TEXT);
        add(questionLabel, BorderLayout.CENTER);

		txtAnswer = new ETextField(15);
		txtAnswer.setText((String) type.getAnswer());
		txtAnswer.addChangeListener(this);
		add(txtAnswer, BorderLayout.EAST);
	}

	/**
	 * Notifies a listeners that a textfield has changed it's value
	 *
	 * @param event Event describing the change
	 */
	public void textChanged(TextChangeEvent event) {
		type.setAnswer(txtAnswer.getText());
	}

	/**
	 * Update the question state (i.e. after a model element has been set programatically)
	 */
	public void updateRenderer() {
		txtAnswer.setText((String) getQuestion().getContentType().getAnswer());
	}

	/**
	 * Change the Editable property
	 */
	public void setEditable(boolean editable) {
		txtAnswer.setEditable(editable);
	}

	/**
	 * Get the preferred width of the question label
	 */
	public double getLabelWidth() {
		return questionLabel.getPreferredSize().width;
	}

	/**
	 * Set the width of the question label
	 */
	public void setLabelWidth(double width) {
		Dimension d = new Dimension((int) width, questionLabel.getPreferredSize().height);
		questionLabel.setMinimumSize(d);
		questionLabel.setPreferredSize(d);
		questionLabel.setMaximumSize(d);
	}

	/**
	 * Get the size of the answer space
	 */
	public double getAnswerSpaceWidth() {
		return txtAnswer.getPreferredSize().width;
	}

	/**
	 * Set the answer space width
	 */
	public void setAnswerSpaceWdith(double width) {
		Dimension d = new Dimension((int) width, txtAnswer.getPreferredSize().height);
		txtAnswer.setMinimumSize(d);
		txtAnswer.setPreferredSize(d);
		txtAnswer.setMaximumSize(d);
	}
	
}

