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

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Vector;

import javax.swing.AbstractCellEditor;
import javax.swing.JComboBox;
import javax.swing.JTable;
import javax.swing.table.TableCellEditor;

import lu.tudor.santec.gecamed.billing.ejb.entity.beans.Invoice;
import lu.tudor.santec.gecamed.billing.gui.act.HospitalisationClassListener;
import lu.tudor.santec.gecamed.core.gui.utils.DefaultComboBoxRenderer;
import lu.tudor.santec.gecamed.patient.ejb.entity.beans.HospitalisationClass;


public class HospClassCellEditor extends AbstractCellEditor implements TableCellEditor, 
																	ActionListener, 
																	HospitalisationClassListener
{
	/* ======================================== */
	// 		CONSTANTS
	/* ======================================== */
	
	private static final long serialVersionUID = 1L;
	
	
	
	/* ======================================== */
	// 		MEMBERS
	/* ======================================== */
	
	private JComboBox 	clazzBox;
	private boolean 	ambulant;
	
	
	
	/* ======================================== */
	// 		CONSTRUCTORS
	/* ======================================== */
	
	public HospClassCellEditor (Vector<String> clazzes)
	{
		ambulant = true;
		
		// if the invoice is a hospitalisation, the combo box is needed
		clazzBox = new JComboBox(clazzes);
		clazzBox.setRenderer(new DefaultComboBoxRenderer());
		clazzBox.addActionListener(this);
		clazzBox.removeItem(HospitalisationClass.c_Ambulant);
		
		BillingModule.getInstance().addHospitalisationClassListener(this);
	}
	
	/* ======================================== */
	// 		IMPLEMENTED METHODS
	/* ======================================== */

	public Object getCellEditorValue()
	{
		Object clazz;
		if (ambulant)
			clazz = HospitalisationClass.c_Ambulant;
		else 
			clazz = clazzBox.getSelectedItem();
		return clazz != null ? clazz : "";
	}
	
	
	public void actionPerformed(ActionEvent e)
	{
		if (e.getSource().equals(clazzBox))
			fireEditingStopped();
	}
	
	
	public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column)
	{
		if (value != null
				&& !ambulant)
		{
			clazzBox.setSelectedItem(value);
			return clazzBox;
		}
		else
			return null;
	}


	public void hospitalisationClassChanged(Invoice invoice)
	{
		try 
		{
			if (invoice.getHospitalisationClass().getAcronym().toUpperCase().equals(HospitalisationClass.c_Ambulant))
				 ambulant = true;
			else ambulant = false;
		}
		catch (NullPointerException e)
		{
			ambulant = true;
		}
	}
}
