/*******************************************************************************
 * This file is part of GECAMed.
 * 
 * GECAMed is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License (L-GPL) as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * GECAMed is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License (L-GPL)
 * along with GECAMed.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * GECAMed is Copyrighted by the Centre de Recherche Public Henri Tudor (http://www.tudor.lu)
 * (c) CRP Henri Tudor, Luxembourg, 2008
 *******************************************************************************/
/**
 *
 */
package lu.tudor.santec.gecamed.prescription.gui.widgets.editor;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.text.DateFormat;
import java.util.HashSet;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFormattedTextField;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.DateFormatter;

import lu.tudor.santec.gecamed.core.gui.GECAMedColors;
import lu.tudor.santec.gecamed.core.gui.MainFrame;
import lu.tudor.santec.gecamed.core.gui.utils.IChangeListener;
import lu.tudor.santec.gecamed.prescription.ejb.entity.beans.PrescriptionDrug;
import lu.tudor.santec.gecamed.prescription.ejb.entity.beans.PrescriptionType;
import lu.tudor.santec.gecamed.prescription.ejb.entity.beans.drug.IDrug;
import lu.tudor.santec.gecamed.prescription.ejb.entity.dataclasses.DrugLight;
import lu.tudor.santec.gecamed.prescription.gui.util.NewDrugWorker;
import lu.tudor.santec.gecamed.prescription.gui.widgets.PosologyChooserDialog;
import lu.tudor.santec.gecamed.prescription.gui.widgets.drugbrowser.DrugBrowser;
import lu.tudor.santec.i18n.Translatrix;
import lu.tudor.santec.widgets.gui.ButtonFactory;

import com.jgoodies.forms.builder.ButtonBarBuilder;
import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;

/**
 * The panel for the prescription editor.
 * It shows the editor for doing prescription of different types. There is on the one hand the editor
 * for creating drug prescriptions, including the autocompletion mechanism described in the DrugCellEditor
 * and for any other type of prescription there is a plain textarea to write texts on a prescription.
 * On top of each editor there are two date fields. one for the current date and one for the date
 * representing the duration how long the current prescription is valid.
 * 
 * The AntecedentControler can send an "edit prescription" command. That means that an already saved prescription
 * should be modified. To mark this as a special state of the editor, the background turns green and an 
 * additional button to cancel this  action appears in the bottom. All this is handled by the EditorControler.
 *
 * @author martin.heinemann@tudor.lu
 *
 *
 * @version
 * <br>$Log: EditorPanel.java,v $
 * <br>Revision 1.18  2009-01-19 15:57:57  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.17  2008-12-05 17:35:35  heinemann
 * <br>Rewrite of the prescription module, ... in progress
 * <br>
 * <br>Revision 1.16  2008-10-22 15:46:34  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.15  2008-10-21 12:28:27  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.14  2008-10-14 12:18:28  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.13  2008-09-25 09:43:08  heinemann
 * <br>fixed copyrights
 * <br>
 * <br>Revision 1.12  2008-07-23 15:13:57  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.11  2008-05-13 11:53:41  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.10  2008-05-13 09:33:26  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.9  2008-05-09 15:24:16  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.8  2008-02-11 16:51:50  heinemann
 * <br>moved IChangeListener to core
 * <br>
 * <br>Revision 1.7  2008-01-16 15:33:35  heinemann
 * <br>better documentation
 * <br>
 * <br>Revision 1.6  2007/08/01 07:09:00  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.5  2007/07/04 08:50:50  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.4  2007/03/12 14:32:10  heinemann
 * <br>Complete - # 46: make printed prescriptions editable
 * <br>http://santec.tudor.lu:8888/gecamed/ticket/46
 * <br>
 * <br>Revision 1.3  2007/03/07 09:45:05  heinemann
 * <br>bug fixes
 * <br>
 * <br>Revision 1.2  2007/03/02 08:28:42  hermen
 * <br>initial checkin after the merge of PatientModuleRebuild with the main HEAD
 * <br>
 * <br>Revision 1.1.2.13  2007/02/21 10:00:40  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.1.2.12  2007/01/24 12:48:56  heinemann
 * <br>consultation and prescription update control.
 * <br>Modifications are displayed.
 * <br>And Incidents are not created if nothing has been entered in consultation, accident and prescription
 * <br>
 * <br>Revision 1.1.2.11  2007/01/22 12:21:15  heinemann
 * <br>Complete - # 41: Print empty prescription
 * <br>http://santec.tudor.lu:8888/gecamed/ticket/41
 * <br>Added button to the navi bar
 * <br>
 * <br>Revision 1.1.2.10  2007/01/08 09:51:59  heinemann
 * <br>Incomplete - # 21: Context Menu -> create new prescription
 * <br>http://santec.tudor.lu:8888/gecamed/ticket/21
 * <br>
 * <br>Revision 1.1.2.9  2007/01/04 13:51:36  heinemann
 * <br>The great space cleaning lady has done a big bunch of refactoring
 * <br>
 * <br>Revision 1.1.2.8  2007/01/04 12:13:53  heinemann
 * <br>Incomplete - # 22: Save consultation after a prescription was printed does not work
 * <br>http://santec.tudor.lu:8888/gecamed/ticket/22
 * <br>
 * <br>fixed and some other changes like the behaviour of the prescription editor in case of printing and afterwards saving the consultation etc
 * <br>
 * <br>Revision 1.1.2.7  2006/12/28 15:47:14  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.1.2.6  2006/12/28 10:32:26  heinemann
 * <br>bug fixing and template improvements
 * <br>
 * <br>Revision 1.1.2.5  2006/12/22 07:48:09  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.1.2.4  2006/12/21 14:26:43  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.1.2.3  2006/12/19 14:53:05  heinemann
 * <br>printing etc
 * <br>
 * <br>Revision 1.1.2.2  2006/12/15 15:59:11  heinemann
 * <br>presc
 * <br>
 * <br>Revision 1.1.2.1  2006/12/14 09:34:01  heinemann
 * <br>many changes
 * <br>
 */
public class EditorPanel extends JPanel implements DocumentListener, IChangeListener {

	/* ******************************************************
	 * Class Members
	 */

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;
	private EditorModel model;


	private final boolean OPAQUE = false;
	private JFormattedTextField dateField;
	private CellConstraints cc;
	private JFormattedTextField expirydateField;
	private String currentType;
	private JPanel metaPanel;
	private DateFormatter dateFormatter;
	private boolean disabledUpdate = true;
	protected JButton templateButton 	= ButtonFactory.createNarrowButton();
	protected JButton printButton 		= ButtonFactory.createNarrowButton();
	protected JButton cancelButton 		= ButtonFactory.createNarrowButton();
	private EditorDrugTableModel drugTableModel;
	private DrugInputComponent drugInputComponent;
	private ButtonBarBuilder bottomButtonBar;
	private JPanel centerPanel;
	private JPanel mainPanel;
	protected JCheckBox chronicalCheckBox;

	/* -------------------------------------------------------
	 * End of Class Members
	 * ********************************************************/

	/**
	 * @param model
	 */
	public EditorPanel(EditorModel model, EditorDrugTableModel drugTableModel) {
		/* ====================================================== */
		this.model = model;
		this.drugTableModel = drugTableModel;
		model.addChangeListener(this);
		initComponent();
		/* ====================================================== */
	}

	/* *************************************************************
	 * Methods
	 */


	/**
	 * Switch the type of prescription for the editor component
	 *
	 * @param type
	 */
	public void switchType(String type) {
		/* ====================================================== */
		this.currentType = type;

		try {
			metaPanel.removeAll();
		} catch (Exception e) {
		}

		// show panel
			metaPanel.add(drugInputComponent.getPanel(type));

		metaPanel.validate();
		metaPanel.updateUI();



		/* ====================================================== */
	}



	/**
	 * init the components
	 */
	private void initComponent() {
		/* ====================================================== */
		this.setLayout(new BorderLayout(0, 3));
		this.setOpaque(false);
		/* ------------------------------------------------------- */
		// create a panel for the header and the rest
		/* ------------------------------------------------------- */
		this.mainPanel = new JPanel(new BorderLayout(0, 2));
		this.mainPanel.setOpaque(false);
		/* ------------------------------------------------------- */
		// a label in the header
		/* ------------------------------------------------------ */
		JPanel header = new JPanel(new BorderLayout());
		header.add(new JLabel(
				Translatrix.getTranslationString("prescription.name") +":"),
				BorderLayout.CENTER);
		header.setOpaque(true);
		header.setBackground(GECAMedColors.c_GECAMedDarkerBackground);
		/* ------------------------------------------------------- */
		this.add(header, 	BorderLayout.NORTH);
		/* ------------------------------------------------------- */
		this.add(mainPanel, BorderLayout.CENTER);
		/* ------------------------------------------------------- */
		this.setBorder(BorderFactory.createLineBorder(GECAMedColors.c_GECAMedDarkerBackground));
		/* ------------------------------------------------------- */
		// a panel for the button bar and the form
		/* ------------------------------------------------------- */
		this.centerPanel = new JPanel();
		/* ------------------------------------------------------- */
		// set the formlayout
		/* ------------------------------------------------------- */
		centerPanel.setLayout(new FormLayout(
				// cols
				"2dlu," +
				"fill:pref:grow," +
				"1dlu," +
				"fill:pref:grow," +
				"2dlu",
				// rows
				"1dlu," +			// 1
				"fill:pref," +		// 2
				"2dlu," +			// 3
				"fill:pref:grow," +	// 4
				"1dlu," +			// 5
				"fill:pref," +		// 6
				"1dlu"));			// 7
		
		centerPanel.setBackground(Color.WHITE);
		mainPanel.add(centerPanel, BorderLayout.CENTER);
		/* ------------------------------------------------------ */
//		this.setBorder(BorderFactory.createTitledBorder(
//				Translatrix.getTranslationString("prescription.name")));

		this.cc = new CellConstraints();
		/* ------------------------------------------------------ */
		/* ------------------------------------------------------ */
		this.dateFormatter = new DateFormatter(
				DateFormat.getDateInstance(DateFormat.SHORT, Translatrix.getLocale()));

//		dateFormatter.setAllowsInvalid(false);
		/* ------------------------------------------------------- */
		// create the date panel
		/* ------------------------------------------------------- */
		createDatePanel();
		/* ------------------------------------------------------- */
		// create the expiry date panel
		/* ------------------------------------------------------- */
		createExpiryDatePanel();
		/* ------------------------------------------------------- */
		// init the input panel
		/* ------------------------------------------------------- */
		this.drugInputComponent = new DrugInputComponent(this.drugTableModel);

		this.drugInputComponent.getTextArea().getDocument().addDocumentListener(this);


		this.metaPanel = new JPanel(new BorderLayout());
		centerPanel.add(metaPanel, cc.xywh(2, 4, 3, 2));

		/* ------------------------------------------------------- */
		// create the button panel
		/* ------------------------------------------------------- */
		createButtonPanel();

		initDrugTableListener();
		/* ------------------------------------------------------- */
		/* ====================================================== */
	}


	/**
	 * Create the button panel for the bottom
	 * save and templates
	 */
	private void createButtonPanel() {
		/* ============================================= */
		this.chronicalCheckBox = new JCheckBox(Translatrix.getTranslationString("prescription.buttons.chronical"));
		
		chronicalCheckBox.setOpaque(false);
		
//		this.bottomButtonBar = new ButtonBarBuilder();
		/* ------------------------------------------------------- */
//		cancelButton.setVisible(false);
//		bottomButtonBar.addGridded(templateButton);
//		bottomButtonBar.addGlue();
//		bottomButtonBar.addGridded(cancelButton);
//		bottomButtonBar.addGlue();
//		bottomButtonBar.addGridded(printButton);
//		/* ------------------------------------------------------- */
//		bottomButtonBar.getPanel().setOpaque(false);
//
		setCancelButtonVisible(false);
//		this.add(bottomButtonBar.getPanel(), cc.xywh(2, 6, 3, 1));
		/* ------------------------------------------------------ */
		// create the actions for the buttons
		// --> is done in PrescriptionTab (print, template)
		// --> cancel in EditorControler



		/* ============================================= */
	}

	protected void setCancelButtonVisible(boolean b) {
		/* ================================================== */
		try {
			this.remove(this.bottomButtonBar.getPanel());
			this.bottomButtonBar.getPanel().remove(cancelButton);
		} catch (Exception e) {
		}
		
		this.bottomButtonBar = new ButtonBarBuilder();
		bottomButtonBar.addFixed(chronicalCheckBox);
		
		bottomButtonBar.addGlue();
		/* ------------------------------------------------------- */
		if (b) {
//			bottomButtonBar.addGlue();
			bottomButtonBar.addFixed(cancelButton);
			bottomButtonBar.addUnrelatedGap();
		}
		bottomButtonBar.addFixed(printButton);
//		bottomButtonBar.addGlue();
		bottomButtonBar.addRelatedGap();
		bottomButtonBar.addFixed(templateButton);
		bottomButtonBar.addRelatedGap();
		/* ------------------------------------------------------- */
		bottomButtonBar.getPanel().setOpaque(false);

//		this.add(bottomButtonBar.getPanel(), cc.xywh(2, 6, 3, 1));
		mainPanel.add(bottomButtonBar.getPanel(), BorderLayout.NORTH);
		
		centerPanel.revalidate();
		/* ================================================== */
	}
	
	
//	/**
//	 * Create the input panel
//	 */
//	private void createInputPanel() {
//		/* ============================================= */
//		// first, create the text panel
//		this.textPanel = new JPan el(new BorderLayout());
//		this.textTextArea = new UndoTextArea(new UndoManager());
//		this.textTextArea.setLineWrap(true);
//		this.textTextArea.getDocument().addDocumentListener(this);
//		/* ------------------------------------------------------ */
//		JScrollPane tScroll = new JScrollPane(textTextArea);
//		tScroll.setVerticalScrollBarPolicy(
//				ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
//		/* ------------------------------------------------------ */
//		textPanel.add(tScroll);
//
//		// second create the drug input panel
//		createDrugPanel();
//
//
//
//		/* ------------------------------------------------------ */
//		/* ------------------------------------------------------ */
//		// metapanel to switch
//		this.metaPanel = new JPanel(new BorderLayout());
//		this.add(metaPanel, cc.xywh(2, 4, 3, 1));
//
//		/* ============================================= */
//	}
//
//
//
//	/**
//	 * Create the drug panel
//	 */
//	private void createDrugPanel() {
//		/* ====================================================== */
//		this.drugPanel = new JPanel(new BorderLayout());
//
//		this.drugTable = new JTable();
//
//		/* ------------------------------------------------------ */
//		JScrollPane dScroll = new JScrollPane(drugTable);
//		dScroll.setVer ticalScrollBarPolicy(
//				ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
//		dScroll.getViewport().setBackground(GECAMedColors.c_ScrollPaneBackground);
//		dScroll.setAutoscrolls(true);
//		/* ------------------------------------------------------ */
//
//		drugTable.setModel(drugTableModel);
//		drugTable.setTableHeader(null);
//		drugTable.getColumnModel().getColumn(0).setCellRenderer(new DrugCellRenderer());
//		drugTable.getColumnModel().getColumn(0).setCellEditor(new DrugCellEditor());
//
//
//		/* ------------------------------------------------------ */
//		drugPanel.add(dScroll);
//		/* ====================================================== */
//	}
//

	/**
	 * Create the panel for the date field
	 */
	private void createDatePanel() {
		/* ====================================================== */
//		 create panels for date
		JPanel datePanel = new JPanel(new BorderLayout());
		datePanel.setOpaque(OPAQUE);
		datePanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
		/* ------------------------------------------------------ */
		// the label
		JLabel dLabel = new JLabel(
				Translatrix.getTranslationString("prescription.name.date")+ ":");
		dLabel.setFont(new Font("Dialog", Font.PLAIN, 10));

		JPanel dLabelPanel = new JPanel(new BorderLayout());
		dLabelPanel.add(dLabel, BorderLayout.WEST);
		dLabelPanel.setOpaque(OPAQUE);
		datePanel.add(dLabelPanel, BorderLayout.NORTH);

		/* ------------------------------------------------------ */
		/* ------------------------------------------------------ */
		// the textfield
		this.dateField = new JFormattedTextField(dateFormatter);
		dateField.setBorder(null);
		dateField.setHorizontalAlignment(JTextField.RIGHT);

		datePanel.add(dateField, BorderLayout.CENTER);
		dateField.getDocument().addDocumentListener(this);
		/* ------------------------------------------------------ */
		// add to the main panel
		centerPanel.add(datePanel, cc.xy(2, 2));
		/* ====================================================== */
	}

	/**
	 * create the panel for the expiry date field
	 */
	private void createExpiryDatePanel() {
		/* ====================================================== */
//		 create panels for date
		JPanel datePanel = new JPanel(new BorderLayout());
		datePanel.setOpaque(OPAQUE);
		datePanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
		/* ------------------------------------------------------ */
		// the label
		JLabel dLabel = new JLabel(
				Translatrix.getTranslationString("prescription.name.expirydate")+ ":");
		dLabel.setFont(new Font("Dialog", Font.PLAIN, 10));

		JPanel dLabelPanel = new JPanel(new BorderLayout());
		dLabelPanel.add(dLabel, BorderLayout.WEST);
		dLabelPanel.setOpaque(OPAQUE);
		datePanel.add(dLabelPanel, BorderLayout.NORTH);

		/* ------------------------------------------------------ */
		/* ------------------------------------------------------ */
		// the textfield

		this.expirydateField = new JFormattedTextField(dateFormatter);


		/* ------------------------------------------------------ */
		expirydateField.setBorder(null);
		expirydateField.setHorizontalAlignment(JTextField.RIGHT);




		datePanel.add(expirydateField, BorderLayout.CENTER);
		expirydateField.getDocument().addDocumentListener(this);
		/* ------------------------------------------------------ */
		// add to the main panel
		centerPanel.add(datePanel, cc.xy(4, 2));
		/* ====================================================== */
	}



	/**
	 * Create a mouselister for the drugTable
	 * for posology chooser and cefip browser
	 */
	private void initDrugTableListener() {
		/* ============================================= */
		drugInputComponent.getTable().addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent e) {

				if (SwingUtilities.isLeftMouseButton(e)) {
					JTable tb = drugInputComponent.getTable();
					if (tb.columnAtPoint(e.getPoint()) == 1) {
						/* ------------------------------------------------------ */
						int row = tb.rowAtPoint(e.getPoint());
						// if the view is not locked by a persisted prescription
						if (!model.getPrescription().isPersistent() &&
								(model.getPrescription().getPrintPrescriptions() == null
								|| model.getPrescription().getPrintPrescriptions().size() == 0)) {
							if (row%2 == 0) {
								// show the cefip browser
								showCefipBrowser(row);
							}else {
								// show the posology chooser
								showPosologyChooser(row);
							}
						}
						/* ------------------------------------------------------ */
					}
				}
			}
		});

		/* ------------------------------------------------------ */
		// key listeners
		drugInputComponent.getTable().addKeyListener(new KeyListener() {

			public void keyTyped(KeyEvent e) {
				if (e.getKeyCode() == KeyEvent.VK_ENTER)
					e.consume();
			}
			public void keyPressed(KeyEvent e) {
				if (e.getKeyCode() == KeyEvent.VK_ENTER)
					e.consume();
			}
			public void keyReleased(KeyEvent e) {
				if (e.getKeyCode() == KeyEvent.VK_ENTER) {
					e.consume();
					/* ------------------------------------------------------ */
					JTable tb = drugInputComponent.getTable();

					if (tb.getSelectedColumn() == 1) {
						/* ------------------------------------------------------ */
						int row = tb.getSelectedRow();
						if (row%2 == 0) {
							// show the cefip browser
							showCefipBrowser(row);
						}else {
							// show the posology chooser
							showPosologyChooser(row);
						}
						/* ------------------------------------------------------ */
					}
				}
			}
		});


		/* ============================================= */
	}



	public void changedUpdate(DocumentEvent e) {
		/* ============================================= */
		updateModel();
		/* ============================================= */
	}

	public void insertUpdate(DocumentEvent e) {
		/* ============================================= */
		updateModel();
		/* ============================================= */
	}

	public void removeUpdate(DocumentEvent e) {
		/* ============================================= */
		updateModel();
		/* ============================================= */
	}


	private void showPosologyChooser(int row) {
		/* ====================================================== */
		String pos = PosologyChooserDialog.getInstance().showDialog(MainFrame.getInstance());
		if (pos != null) {
			// add the posology to the drugTableModel
			drugTableModel.setValueAt(
					(drugTableModel.getValueAt(row, 0) != null
							&& !drugTableModel.getValueAt(row, 0).equals("")
							? drugTableModel.getValueAt(row, 0)+ "\n" :  "")
							+ pos
					, row, 0);
		}
		/* ====================================================== */
	}

	/**
	 * @param row to know where to return the selected drug
	 */
	private void showCefipBrowser(int row) {
		/* ====================================================== */
		drugInputComponent.getTable().getColumnModel().getColumn(0).getCellEditor().stopCellEditing();
		DrugBrowser nb = DrugBrowser.getInstance();
		DrugLight dl = (DrugLight) drugTableModel.getValueAt(row, 0);
		/* ------------------------------------------------------- */

		IDrug iD = nb.showDialog((dl != null ? dl.getName() : ""));
		/* ------------------------------------------------------- */
		if (iD != null) {
			drugTableModel.setValueAt(NewDrugWorker.IDrug2DrugLight(iD), row, 0);
		}
		/* ====================================================== */
	}


	/**
	 * Write the data to the model
	 */
	private void updateModel() {
	/* ====================================================== */
		if (!disabledUpdate) {
			model.setDate((java.util.Date) dateField.getValue());
			if (expirydateField.getText() == null || "".equals(expirydateField.getText().trim()))
					model.setExpiryDate(null);
			else
				model.setExpiryDate((java.util.Date) expirydateField.getValue());
			
			
			if (currentType.equals(PrescriptionType.MEDICINE)) {
	//			model.setTextContent("");
	//			model.setDrugs(drugs);
//				model.setTextContent(drugTextArea.getText());
			} else {
//				model.setDrugs(null);
				model.setTextContent(this.drugInputComponent.getTextArea().getText());
			}
		}
	/* ====================================================== */
	}

	/* (non-Javadoc)
	 * @see lu.tudor.santec.gecamed.prescription.gui.util.IChangeListener#fireEvent()
	 */
	public void fireEvent() {
		/* ============================================= */
		// update the panel
		this.disabledUpdate = true;
		this.dateField.setValue(model.getPrescription().getPrescriptionDate());
		this.expirydateField.setValue(model.getPrescription().getExpiryDate());
		if (model.getPrescription().getIsChronic() != null)
			this.chronicalCheckBox.setSelected(model.getPrescription().getIsChronic());
		else
			this.chronicalCheckBox.setSelected(false);
		/* ------------------------------------------------------ */
		if (currentType.equals(PrescriptionType.MEDICINE)) {
			/* ------------------------------------------------------ */
//			this.drugTextArea.setText(model.getPrescription().getTextContent());
			// TODO drug Editor!!!!
			try {
				/* ------------------------------------------------------- */
//				drugTableModel.setNewDrugs(
//						new HashSet<PrescriptionDrug>(
//								model.getPrescription()
//								.getPrescriptionDrugs()));
				/* ------------------------------------------------------- */
				// this is for modifying saved prescriptions
				/* ------------------------------------------------------- */
				drugTableModel.addDrugs(new HashSet<PrescriptionDrug>(
								model.getPrescription()
								.getPrescriptionDrugs()));
				/* ------------------------------------------------------- */
			} catch (NullPointerException en) {
				/* ------------------------------------------------------- */
				drugTableModel.reset();
				/* ------------------------------------------------------- */
			}
			/* ------------------------------------------------------ */
		} else {
			/* ------------------------------------------------------ */
			this.drugInputComponent.getTextArea()
				.setText(model.getPrescription().getTextContent());
			/* ------------------------------------------------------ */
		}

		// disable the view in case of an persisted and printed prescription and
		// if not persisted, enable
//		if (!model.isOld() &&
//				!model.getPrescription().isPersistent()
//				||
//				// or if persisted but not printed
//				(model.getPrescription().isPersistent()
//						&&
//					(model.getPrescription().getPrintPrescriptions() == null
//					|| model.getPrescription().getPrintPrescriptions().size() == 0))) {
//			this.setEnableEditorArea(true);
//		}
//		else {
//			this.setEnableEditorArea(false);
//		}

		this.disabledUpdate = false;
		/* ============================================= */
	}

	public void reset() {
		/* ============================================= */
		drugTableModel.reset();
		/* ============================================= */
	}

	/**
	 * enables/disables the editor area
	 *
	 * @param b
	 */
	public void setEnableEditorArea(boolean b) {
		/* ============================================= */
		this.drugInputComponent.setEnable(b);

		dateField.setEnabled(b);
		expirydateField.setEnabled(b);
		/* ============================================= */
	}

	public void setEditorBackground(Color color) {
		/* ====================================================== */
		this.centerPanel.setBackground(color);
		/* ====================================================== */
	}

	/* -------------------------------------------------------
	 * End of Class Members
	 * ********************************************************/

}
