package lu.tudor.santec.gecamed.formeditor.gui.component;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JComponent;
import javax.swing.JTextField;
import javax.swing.text.JTextComponent;

import lu.tudor.santec.gecamed.formeditor.gui.controller.FormController;
import lu.tudor.santec.gecamed.formeditor.gui.model.FormModel;
import lu.tudor.santec.i18n.Translatrix;

public class EditableTextField extends EditableComponent {
	/**
	 * @author Jens Ferring
	 * 
	 * This represents a JTextField as EditableComponent.
	 */
	private static final long serialVersionUID = 1L;
	
	public static final int LISTENER_METHOD_SIZE = 1;
	public static final int CARET_UPDATED = SUPER_LISTENER_METHOD_SIZE;

	
	public EditableTextField () 
	{
		super();
		this.component = new JTextField();
	}
	
	public EditableTextField (JComponent component)
	{
		super();
		this.component = component;
	}
	
	@Override
	protected void initType()
	{
		// the key-listener is add to synchronize the TextField in the settings panel with this TextField
		getTextComponent().addKeyListener(new KeyListener() 
		{
			public void keyTyped(KeyEvent e) {}
			public void keyPressed(KeyEvent e) {}
			
			public void keyReleased(KeyEvent e) 
			{
				((JTextComponent)optionPanel.getCaptionText()).setText(getText());
			}
		});
		
		super.initType();
	}
	
	
	@Override
	public String getText() 
	{
		return getTextComponent().getText();
	}

	
	@Override
	public void setText(String text) 
	{
		getTextComponent().setText(text);
	}

	
	@Override
	public String getComponentType () 
	{
		return "textfield";
	}
	
	
	@Override
	public JComponent copyComponent (FormModel model) 
	{
		JTextComponent tf = (JTextComponent) component;
		
		FormController controller = new FormController(model);
		tf.addCaretListener(controller);
		controller.setCodeAt(FormController.CARET_UPDATED, getScriptAt(CARET_UPDATED));
		addDefaultListener(tf, controller);
		
		return tf;
	}

	
	@Override
	protected void addListenerMethodNames() {
		listenerMethodNames[CARET_UPDATED] = "caretUpdated";
	}

	
	@Override
	public int getListenerMethodSize() {
		return LISTENER_METHOD_SIZE;
	}

	
	@Override
	public String getStructure() {
		return "";
	}
	
	
	@Override
	public void setStructure(String text) {}
	
	
	@Override
	public String getTypeTranslation () 
	{
		return Translatrix.getTranslationString("formeditor.add_textfield");
	}

	@Override
	public Boolean isComponentTypeStoredInDBByDefault () {
		return true;
	}
	
	
	protected JTextComponent getTextComponent ()
	{
		return (JTextComponent) component;
	}
}
