package lu.tudor.santec.gecamed.billing.gui.act;

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.ParseException;

import javax.swing.AbstractCellEditor;
import javax.swing.JTable;
import javax.swing.table.TableCellEditor;
import javax.swing.text.JTextComponent;

import lu.tudor.santec.gecamed.core.gui.widgets.NumberField;


public class AmountEditor extends AbstractCellEditor implements TableCellEditor, 
																KeyListener, 
																ActionListener
{
	/* ======================================== */
	// 		CONSTANTS
	/* ======================================== */
	
	private static final long serialVersionUID = 1L;
	
	private static DecimalFormat	formatter = createDeciamlFormat();
	
	
	
	/* ======================================== */
	// 		MEMBERS
	/* ======================================== */
	
	private NumberField amountField;
	
	
	
	/* ======================================== */
	// 		CONSTRUCTORS
	/* ======================================== */
	
	public AmountEditor ()
	{
		amountField = new NumberField(5, true, true);
		amountField.addActionListener(this);
		amountField.addKeyListener(this);
	}
	
	
	
	/* ======================================== */
	// 		IMPLEMENTED METHODS
	/* ======================================== */
	
	public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column)
	{
		amountField.setText(formatter.format(value));
		
		return amountField;
	}
	
	
	public Object getCellEditorValue()
	{
		try 
		{
			Number n = formatter.parse(amountField.getText());
			if (n instanceof Double)
				return n;
			else 
				return Double.valueOf(n.doubleValue());
		}
		catch (ParseException e)
		{
			// empty string was entered
			return null;
		}
	}
	
	
	public JTextComponent getTextField ()
	{
		return amountField;
	}


	public void actionPerformed(ActionEvent e)
	{
		stopCellEditing();
	}


	public void keyTyped(KeyEvent e)
	{
		if (	   e.getKeyCode() == KeyEvent.VK_TAB
				|| e.getKeyCode() == KeyEvent.VK_ENTER)
			this.stopCellEditing();
		else if (e.getKeyCode() == KeyEvent.VK_ESCAPE)
			this.cancelCellEditing();
	}


	public void keyPressed(KeyEvent e) {}
	public void keyReleased(KeyEvent e) {}
	
	
	
	/* ======================================== */
	// 		HELP METHODS
	/* ======================================== */
	
	private static DecimalFormat createDeciamlFormat ()
	{
		DecimalFormatSymbols dfs = new DecimalFormatSymbols();
		dfs.setDecimalSeparator(',');
		return new DecimalFormat("#.##", dfs);
	}
}
