package nl.nikhef.safaripark.editpane;

import java.awt.BorderLayout;
import java.text.DecimalFormat;

import javax.swing.JFormattedTextField;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.NumberFormatter;

import nl.nikhef.sfp.ddmi.DDMIValue;

@SuppressWarnings("serial")
public class DecimalEditor extends ValueEditor implements DocumentListener {

	
	private JFormattedTextField _tf;
	private boolean _ignoreEvents = false;
	
	public DecimalEditor(EditorContext ctx, DDMIValue value, JLabel label) {
		super(ctx, value, label);
		setLayout(new BorderLayout());
		DecimalFormat dec = new DecimalFormat();
		dec.setMaximumFractionDigits(6);
		dec.setGroupingUsed(false);
		_tf = new JFormattedTextField(new NumberFormatter(dec));
		add(_tf, BorderLayout.CENTER);
		_tf.getDocument().addDocumentListener(this);
		clearValue();
	}

	@Override
	protected void updateValue() 
	{
		_tf.setEnabled(isValueValid());
		_tf.setEditable(value.isWritable());
		_ignoreEvents = true;
		_tf.setValue(getAsDecimal());		
		_ignoreEvents = false;
	}

	@Override
	protected void clearValue() 
	{
		_tf.setEnabled(false);
		_tf.setEditable(false);
		_ignoreEvents = true;
		_tf.setText("");		
		_ignoreEvents = false;
	}

	
	private void valueUpdated() {
		if (_ignoreEvents) return;
		float v = Number.class.cast(_tf.getValue()).floatValue();
		setAsDecimal(v);
		// setAsString(_tf.getText());
	}
	

	@Override
	public void insertUpdate(DocumentEvent e) {
		valueUpdated();
	}

	

	@Override
	public void removeUpdate(DocumentEvent e) {
		valueUpdated();
	}

	@Override
	public void changedUpdate(DocumentEvent e) {
		valueUpdated();
	}
	

}
