/*******************************************************************************
 * 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.template;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JSeparator;
import javax.swing.SwingUtilities;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

import lu.tudor.santec.gecamed.core.gui.GECAMedAction;
import lu.tudor.santec.gecamed.core.gui.GECAMedIconNames;
import lu.tudor.santec.gecamed.core.gui.GECAMedModule;
import lu.tudor.santec.gecamed.core.gui.MainFrame;
import lu.tudor.santec.gecamed.core.gui.widgets.StatusBar;
import lu.tudor.santec.gecamed.core.utils.ManagerFactory;
import lu.tudor.santec.gecamed.office.ejb.entity.beans.Physician;
import lu.tudor.santec.gecamed.prescription.ejb.entity.beans.PrescriptionDrug;
import lu.tudor.santec.gecamed.prescription.ejb.entity.beans.PrescriptionTemplate;
import lu.tudor.santec.gecamed.prescription.ejb.entity.beans.TemplateDrug;
import lu.tudor.santec.gecamed.prescription.ejb.session.beans.PrescriptionManagerBean;
import lu.tudor.santec.gecamed.prescription.ejb.session.interfaces.PrescriptionManager;
import lu.tudor.santec.gecamed.prescription.gui.PrescriptionIcons;
import lu.tudor.santec.gecamed.prescription.gui.widgets.drugbrowser.NameFilter;
import lu.tudor.santec.gecamed.prescription.gui.widgets.editor.EditorDrugTableModel;
import lu.tudor.santec.gecamed.prescription.gui.widgets.editor.EditorModel;
import lu.tudor.santec.gecamed.prescription.gui.widgets.editor.template.editor.TemplateEditor;
import lu.tudor.santec.gecamed.prescription.gui.widgets.editor.template.editor.TemplateEditorModel;
import lu.tudor.santec.i18n.Translatrix;

import org.apache.log4j.Logger;


/**
 * Controler class for the template component of the prescription module.
 * It handles the actions on the list and the interaction between the templates and the prescription editor.
 * 
 * 
 * @author martin.heinemann@tudor.lu
 *
 *
 * @version
 * <br>$Log: TemplateControler.java,v $
 * <br>Revision 1.18  2013-12-27 18:09:25  donak
 * <br>Cleanup of imports
 * <br>
 * <br>Revision 1.17  2013-07-15 06:18:35  ferring
 * <br>logging changed
 * <br>
 * <br>Revision 1.16  2010-07-22 09:49:39  troth
 * <br>add implementation - # 239: Prescription Templates linked to physician
 * <br>http://santec.tudor.lu/trac/gecamed/ticket/239
 * <br>
 * <br>Revision 1.15  2010-03-30 10:35:17  troth
 * <br>Redesign of the prescription view - add Icons
 * <br>
 * <br>Revision 1.14  2008-10-22 15:46:34  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.13  2008-09-25 09:43:07  heinemann
 * <br>fixed copyrights
 * <br>
 * <br>Revision 1.12  2008-05-13 11:53:41  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.11  2008-05-13 09:33:26  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.10  2008-01-15 13:40:35  heinemann
 * <br>better documentation
 * <br>
 * <br>Revision 1.9  2007-11-20 08:58:55  hermen
 * <br>moved Managerfactory to core.utils and refactured code to use ManagerFactory instead of context.lookup
 * <br>
 * <br>Revision 1.8  2007/07/04 08:50:50  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.7  2007/07/03 12:35:29  heinemann
 * <br>system.out removed
 * <br>
 * <br>Revision 1.6  2007/03/30 12:18:00  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.5  2007/03/14 09:07:36  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.4  2007/03/12 14:33:58  heinemann
 * <br>Incomplete - # 5: Implement the filter function for the prescription templates
 * <br>http://santec.tudor.lu:8888/gecamed/ticket/5
 * <br>
 * <br>Revision 1.3  2007/03/12 09:03:30  hermen
 * <br>added time settong for OSD
 * <br>
 * <br>Revision 1.2  2007/03/02 08:28:39  hermen
 * <br>initial checkin after the merge of PatientModuleRebuild with the main HEAD
 * <br>
 * <br>Revision 1.1.2.11  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.10  2007/01/11 10:41:13  heinemann
 * <br>Complete - # 51: Create preview for prescription templates
 * <br>http://santec.tudor.lu:8888/gecamed/ticket/51
 * <br>
 * <br>Revision 1.1.2.9  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.8  2007/01/04 13:51:37  heinemann
 * <br>The great space cleaning lady has done a big bunch of refactoring
 * <br>
 * <br>Revision 1.1.2.7  2007/01/03 15:49:20  heinemann
 * <br>mouselistener for the context menu changed to mouseReleased
 * <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/21 15:56:06  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:31  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 TemplateControler {


	/* *****************************************************************
	 * Class members
	 */

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

	/** the logger Object for this class */
	private static Logger logger = Logger.getLogger(TemplateControler.class.getName());

	private TemplateModel templateModel;

	private TemplatePanel panel;

	private List<ITemplateReceiver> receivers = new ArrayList<ITemplateReceiver>();

	private TemplateEditorModel templateEditorModel;

	private EditorDrugTableModel drugTemplateEditorTableModel;

	private TemplateEditor editorPanel;

	private String currentType;

	private JPopupMenu editorPopup;

	private JMenuItem editMenuItem;

	private GECAMedAction newAction;

	private JMenuItem mergeMenuItem;

	private JMenuItem deleteMenuItem;

//	private JMenuItem undeleteMenuItem;

//	private JMenuItem deleteMarkedMenuItem;

	private NameFilter nameFilter;

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

	/**
	 * 
	 */
	public TemplateControler() {
		/* ====================================================== */
		// create a model
		this.templateModel = new TemplateModel(this);
		// create a panel
		this.panel = new TemplatePanel(templateModel);

		this.nameFilter = new NameFilter();

		templateModel.installFilter(nameFilter, 0);

		initTableListener();
		initFilterListener();

		/* ------------------------------------------------------ */
		// the editor
		initEditor();

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




	/* *************************************************************
	 * methods
	 */

	/**
	 * Get the TemplatePanel
	 *
	 * @return
	 */
	public JPanel getPanel() {
		/* ====================================================== */
		return this.panel;
		/* ====================================================== */
	}


	/* ***************************************************************
	 * Template receivers
	 * ************************************************************* */


	/**
	 *
	 * Add a template receiver, that will receive a selected template
	 *
	 * @param rec
	 */
	public void addTemplateReceiver(ITemplateReceiver rec) {
		/* ====================================================== */
		this.receivers.add(rec);
		/* ====================================================== */
	}

	/**
	 * Remove a template receiver
	 *
	 * @param rec
	 */
	public void removeTemplatereceiver(ITemplateReceiver rec) {
		/* ====================================================== */
		this.receivers.remove(rec);
		/* ====================================================== */
	}


	/* ***************************************************************
	 * update
	 * ************************************************************* */

	/**
	 * Update the lists data for the given type
	 *
	 * @param type
	 */
	public void update(String type) {
		/* ====================================================== */		
		Physician physician  = GECAMedModule.getCurrentPhysician();
		int phyId = 0;
		if(physician != null && physician.isPersistent())
			phyId = physician.getId();
		
		templateModel.setData(type, getManager().getTemplates(type, phyId));
//		templateModel.fireTableDataChanged();
		templateEditorModel.fireDataChanged();
		/* ====================================================== */
	}

	/**
	 * Send template to the receivers
	 *
	 * @param temp
	 */
	protected void sendTemplate(PrescriptionTemplate temp) {
		/* ====================================================== */
		if (receivers != null) {
			/* ------------------------------------------------------ */
			// show warning msg
			if (temp.getWarningMsg() != null
					&& !temp.getWarningMsg().equals("")) {
				/* ------------------------------------------------------ */
				if (temp.getIsWarning()) {
					// open popup with the msg
					JOptionPane.showConfirmDialog(panel, temp.getWarningMsg(),
		                       Translatrix.getTranslationString("prescription.name.warning"),  //$NON-NLS-1$
		                       JOptionPane.PLAIN_MESSAGE,
		                       JOptionPane.WARNING_MESSAGE);
				} else {
					// show toaster
					StatusBar.getInstance().setWarningText(
							temp.getWarningMsg());
				}
				/* ------------------------------------------------------ */
			}

			for(ITemplateReceiver rec : receivers)
				rec.receiveTemplate(temp);
			/* ------------------------------------------------------ */
		}
		/* ====================================================== */
	}


	/**
	 * Switch the type of prescription
	 *
	 * @param type
	 */
	public void switchType(String type) {
		/* ====================================================== */
		this.templateModel.switchType(type);
		update(type);
		this.currentType = type;
		panel.filterTextField.setText("");
		/* ====================================================== */
	}

	/**
	 * Open the TemplateEditor
	 */
	public void showEditor() {
		/* ====================================================== */
		this.templateEditorModel.setType(this.currentType);
		templateEditorModel.reset();
		drugTemplateEditorTableModel.reset();

		this.editorPanel.pack();

		MainFrame.showDialogCentered(this.editorPanel);
		/* ====================================================== */
	}



	/* -------------------------------------------------------------
	 * End of methods
	 * **************************************************************/

	/* **************************************************************
	 * Helper
	 */

	/**
	 *
	 * Get a reference to the prescription manager session bean
	 *
	 * @return
	 */
	protected PrescriptionManager getManager() {
		/* ====================================================== */
		return (PrescriptionManager)
			ManagerFactory.getRemote(PrescriptionManagerBean.class);
		/* ====================================================== */

	}

	/**
	 * register a mouselistener to the JTable of the TemplatePanel
	 */
	private void initTableListener() {
		/* ====================================================== */

		// mouselistener
		this.panel.templateTable.addMouseListener(new MouseAdapter () {

			/* (non-Javadoc)
			 * @see java.awt.event.MouseAdapter#mouseClicked(java.awt.event.MouseEvent)
			 */
			@Override
			public void mouseClicked(MouseEvent e) {
				/* ============================================= */
				// double click means
				// send the selected template to the recievers
				if (SwingUtilities.isLeftMouseButton(e)
						&& e.getClickCount() == 2) {
					/* ------------------------------------------------------ */
					sendTemplate(
							templateModel.getTemplateByRow(
									panel.templateTable.getSelectedRow()));
				/* ------------------------------------------------------ */
				}
				// single click will open a preview
				if (SwingUtilities.isLeftMouseButton(e)
						&& e.getClickCount() == 1) {
					/* ------------------------------------------------------ */
						panel.showTemplatePreview(templateModel.getTemplateByRow(
								panel.templateTable.getSelectedRow()), e);
					/* ------------------------------------------------------ */
				}
				/* ============================================= */
			}

		});
		// key Listener
		this.panel.templateTable.addKeyListener(new KeyAdapter() {

			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();
					/* ------------------------------------------------------ */
					sendTemplate(
							templateModel.getTemplateByRow(
									panel.templateTable.getSelectedRow()));
				}
			}
		});
		/* ====================================================== */
	}

	/**
	 * Init the document listener for the filter textfield
	 */
	private void initFilterListener() {
		/* ====================================================== */
		this.panel.filterTextField.getDocument().addDocumentListener(
				new DocumentListener() {

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

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

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

					private void action() {
						/* ====================================================== */
//						int row = templateModel.setFilterText(panel.filterTextField.getText());
//						if (row > -1) {
//							panel.templateTable.setRowSelectionInterval(row, row);
//						}
						templateModel.setFilteringEnabled(true, 0);
						
						nameFilter.setFilter(panel.filterTextField.getText());
						templateModel.update();
						/* ====================================================== */
					}

				});
		/* ====================================================== */
	}


	/* ***************************************************************
	 * ***************************************************************
	 *  Editor methods
	 * ****************************************************************/

	/**
	 * Init the template editor
	 */
	private void initEditor() {
		/* ====================================================== */
		this.drugTemplateEditorTableModel = new EditorDrugTableModel();
		this.templateEditorModel = new TemplateEditorModel();
		this.editorPanel = new TemplateEditor(templateModel, this.templateEditorModel,
				this.drugTemplateEditorTableModel);

		initEditorButtonActions();
		initEditorTableListener();
		initEditorPopup();
		/* ====================================================== */
	}

	/**
	 * Add key and mouselisteners to the template tabel.
	 *
	 * The default behaviour should be:<ul>
	 *  <li>Hitting enter, the selected template is opened in the editor</li>
	 *  <li>double click on a template makes the same</li>
	 *  <li>"delete" will delete the selected templates, with question dialog</li>
	 *  <li>left click opens context menu</li>
	 *  <li></li>
	 *  </ul>
	 */
	private void initEditorTableListener() {
		/* ============================================= */
		editorPanel.getTemplateTable().addKeyListener(new KeyAdapter() {

			/* (non-Javadoc)
			 * @see java.awt.event.KeyAdapter#keyPressed(java.awt.event.KeyEvent)
			 */
			@Override
			public void keyTyped(KeyEvent e) {
				/* ============================================= */
				if (e.getKeyCode() == KeyEvent.VK_ENTER)
				{
					e.consume();
					// open the template in editor
					openTemplateInEditor();
				}
				/* ============================================= */
			}
			@Override
			public void keyPressed(KeyEvent e) {
				/* ============================================= */

				if (e.getKeyCode() == KeyEvent.VK_ENTER)
				{
					e.consume();
					// open the template in editor
					openTemplateInEditor();
				}

				if (e.getKeyCode() == KeyEvent.VK_DELETE) {
					/* ====================================================== */
					deleteSelected();
					/* ====================================================== */
				}
//				if (e.getKeyCode() == KeyEvent.VK_U) {
//					/* ====================================================== */
//					unmarkAsRemoved();
//					/* ====================================================== */
//				}
				/* ============================================= */
			}

		});

		editorPanel.getTemplateTable().addMouseListener(new MouseAdapter() {

			/* (non-Javadoc)
			 * @see java.awt.event.MouseAdapter#mousePressed(java.awt.event.MouseEvent)
			 */
			@Override
			public void mouseReleased(MouseEvent e) {
				/* ============================================= */
				if(SwingUtilities.isLeftMouseButton(e)
						&& e.getClickCount() == 2) {
					/* ------------------------------------------------------ */
					openTemplateInEditor();
					/* ------------------------------------------------------ */
				}  else
					if (e.isPopupTrigger()) {
						/* ------------------------------------------------------ */
						// open popup
						editorPopup.show(editorPanel.getTemplateTable(), e.getX(), e.getY());
						/* ------------------------------------------------------ */
					}

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

			/* (non-Javadoc)
			 * @see java.awt.event.MouseAdapter#mousePressed(java.awt.event.MouseEvent)
			 */
			@Override
			public void mousePressed(MouseEvent e) {
				/* ============================================= */
				if (e.isPopupTrigger()) {
					/* ------------------------------------------------------ */
					// open popup
					editorPopup.show(editorPanel.getTemplateTable(), e.getX(), e.getY());
					/* ------------------------------------------------------ */
				}
				/* ============================================= */
			}



		});

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



	/**
	 * 
	 */
	private void initEditorPopup() {
		/* ====================================================== */

		this.editorPopup = new JPopupMenu();
		// edit
		this.editMenuItem = new JMenuItem(
				Translatrix.getTranslationString("template.buttons.edit"),
				PrescriptionIcons.getMiniIcon(PrescriptionIcons.EDIT_LIST));
		editMenuItem.setMnemonic(KeyEvent.VK_E);

		this.editMenuItem.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				/* ============================================= */
				openTemplateInEditor();
				/* ============================================= */
			}
		});
		// merge
		this.mergeMenuItem = new JMenuItem(
				Translatrix.getTranslationString("template.buttons.merge"),
				PrescriptionIcons.getMiniIcon(PrescriptionIcons.ADD_ITEM));
		mergeMenuItem.setMnemonic(KeyEvent.VK_A);

		this.mergeMenuItem.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				/* ============================================= */
				addTemplatesToCurrent();
				/* ============================================= */
			}
		});
		// delete
		this.deleteMenuItem = new JMenuItem(
				Translatrix.getTranslationString("template.buttons.delete"),
				PrescriptionIcons.getMiniIcon(PrescriptionIcons.BUTTON_CANCEL));
		deleteMenuItem.setMnemonic(KeyEvent.VK_R);

		this.deleteMenuItem.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				/* ============================================= */
				deleteSelected();
				update(currentType);
				/* ============================================= */
			}
		});
//		// undelete
//		this.undeleteMenuItem = new JMenuItem(
//				Translatrix.getTranslationString("template.buttons.undelete"),
//				IconBuilder.getMiniIcon(IconBuilder.BUTTON_UNDO));
//		undeleteMenuItem.setMnemonic(KeyEvent.VK_U);
//
//		this.undeleteMenuItem.addActionListener(new ActionListener() {
//
//			public void actionPerformed(ActionEvent e) {
//				/* ============================================= */
//				unmarkAsRemoved();
//				/* ============================================= */
//			}
//		});
		// ---------
//		// delete marked
//		this.deleteMarkedMenuItem = new JMenuItem(
//				Translatrix.getTranslationString("template.buttons.deletemarked"),
//				IconBuilder.getMiniIcon(IconBuilder.DELETE));
//
//
//		this.deleteMarkedMenuItem.addActionListener(new ActionListener() {
//
//			public void actionPerformed(ActionEvent e) {
//				/* ============================================= */
////				 delete the marked templates
//				templateModel.deleteMarkedTemplates();
//				update(currentType);
//
//				/* ============================================= */
//			}
//		});



		this.editorPopup.add(editMenuItem);
		this.editorPopup.add(newAction);

		this.editorPopup.add(new JSeparator());
		this.editorPopup.add(mergeMenuItem);

		this.editorPopup.add(new JSeparator());
		this.editorPopup.add(deleteMenuItem);
//		this.editorPopup.add(undeleteMenuItem);

//		this.editorPopup.add(new JSeparator());
//		this.editorPopup.add(deleteMarkedMenuItem);
		/* ====================================================== */
	}

	/**
	 * Tries to open a selected template from the table
	 * in the template editor
	 */
	private void openTemplateInEditor() {
		/* ====================================================== */
		try {
			openTemplate(templateModel.getTemplateByRow(
					editorPanel.getTemplateTable().getSelectedRow()));
			} catch (Exception e) {
				e.printStackTrace();
			}
		/* ====================================================== */
	}


	/**
	 * Mark the selected template as deleted
	 */
	private void deleteSelected() {
		/* ====================================================== */
		// mark the selected as removed
		int rows[] =  editorPanel.getTemplateTable().getSelectedRows();
		for (int i = 0; i < rows.length; i++) {
			PrescriptionTemplate t = templateModel.getTemplateByRow(rows[i]);

			if (t != null) {
				/* ------------------------------------------------------ */
				templateModel.deleteTemplate(t);
				/* ------------------------------------------------------ */
			}
		}
		templateModel.fireTableDataChanged();
		editorPanel.getTemplateTable().getSelectionModel().setSelectionInterval(rows[0], rows[0]);
		/* ====================================================== */
	}

//	/**
//	 * Unmark the deleted templates.
//	 */
//	private void unmarkAsRemoved() {
//		/* ====================================================== */
//		// mark the selected as unremoved
//		int rows[] =  editorPanel.getTemplateTable().getSelectedRows();
//		for (int i = 0; i < rows.length; i++) {
//			PrescriptionTemplate t = templateModel.getTemplateByRow(rows[i]);
//
//			if (t != null) {
//				/* ------------------------------------------------------ */
//				templateModel.unmarkDeleted(t);
//				/* ------------------------------------------------------ */
//			}
//		}
//		templateModel.fireTableDataChanged();
//		/* ====================================================== */
//	}


	/**
	 * Adds the selected tempaltes to the current template in the editor
	 */
	private void addTemplatesToCurrent() {
		/* ====================================================== */
		try {
			/* ------------------------------------------------------ */
			int rows[] = editorPanel.getTemplateTable().getSelectedRows();
			for (int i = 0; i < rows.length; i++) {
				/* ------------------------------------------------------ */
				// for each selected template, get the TemplateDrugs
				// and convert them into PrescriptionDrugs

				// get the template
				PrescriptionTemplate temp = templateModel.getTemplateByRow(rows[i]);

				if (temp.getTemplateDrugs() != null) {
					Set<PrescriptionDrug> ds = new HashSet<PrescriptionDrug>();
					for (TemplateDrug t : temp.getTemplateDrugs()) {
						/* ------------------------------------------------------ */
						PrescriptionDrug d = templateDrug2Drug(t);
						ds.add(d);
						/* ------------------------------------------------------ */
					}
					drugTemplateEditorTableModel.addDrugs(ds);
				}
				/* ------------------------------------------------------ */
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		/* ====================================================== */
	}

	/**
	 * Open a template in the editor.<br>
	 * If there are changes in the current template, a question dialog
	 * will appear, that asks whether to save the template or not.
	 *
	 * @param temp
	 */
	private void openTemplate(PrescriptionTemplate temp) {
		/* ====================================================== */
		if (temp != null) {
			/* ------------------------------------------------------ */
			if (templateEditorModel.isModified() ||
					drugTemplateEditorTableModel.isModified()) {
				// open dialog
				int n = JOptionPane.showConfirmDialog(
					    editorPanel,
					    Translatrix.getTranslationString("template.desc.modified"),
					    Translatrix.getTranslationString("template.desc.modified"),
					    JOptionPane.YES_NO_CANCEL_OPTION);
				/* ------------------------------------------------------ */
				if (n == JOptionPane.YES_OPTION) {
					/* ------------------------------------------------------ */
					// save the template
					editorPanel.getSaveButton().doClick();
					/* ------------------------------------------------------ */
				} else
					if (n == JOptionPane.CANCEL_OPTION) {
						// return
						return;
					}
			}
			/* ------------------------------------------------------ */
			// open the template
			templateEditorModel.setTemplate(temp);

			if (temp.getTemplateDrugs() != null) {
				Set<PrescriptionDrug> ds = new HashSet<PrescriptionDrug>();
				for (TemplateDrug t : temp.getTemplateDrugs()) {
					/* ------------------------------------------------------ */
					PrescriptionDrug d = templateDrug2Drug(t);
					ds.add(d);
					/* ------------------------------------------------------ */
				}
				drugTemplateEditorTableModel.setNewDrugs(ds);
			}
			/* ------------------------------------------------------ */
		}
		/* ====================================================== */
	}


	/**
	 * Init the editor's buttons (new,save, close)
	 */
	private void initEditorButtonActions() {
		/* ====================================================== */
//		 an action for the print button
		this.newAction = new GECAMedAction(null,
				"prescription.core.new",
				GECAMedModule.getSmallIcon(
						GECAMedIconNames.ADD_LINE),
				null, // ?
				false, false, false) {

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

					/* (non-Javadoc)
					 * @see lu.tudor.santec.gecamed.core.gui.GECAMedAction#actionPerformed(java.awt.event.ActionEvent)
					 */
					@Override
					public void actionPerformed(ActionEvent p_Event) {
						/* ============================================= */
						drugTemplateEditorTableModel.reset();
						openTemplate(new PrescriptionTemplate());
//						templateEditorModel.reset();
						drugTemplateEditorTableModel.fireTableDataChanged();
						/* ============================================= */
					}
		};
		/* ------------------------------------------------------ */
		editorPanel.getNewButton().setAction(newAction);


		// an action for the save button
		GECAMedAction saveAction = new GECAMedAction(null,
				"prescription.core.save",
				GECAMedModule.getSmallIcon(
						GECAMedIconNames.SAVE),
				null,
				false, false, false) {

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

					/* (non-Javadoc)
					 * @see lu.tudor.santec.gecamed.core.gui.GECAMedAction#actionPerformed(java.awt.event.ActionEvent)
					 */
					@Override
					public void actionPerformed(ActionEvent p_Event) {
						/* ============================================= */

						PrescriptionTemplate template = getCurrentTemplate();

						if (checkTemplate(template)) {
							/* ------------------------------------------------------ */
							// call the manager and persist
							EditorModel.getManager().saveTemplate(template);
							/* ------------------------------------------------------- */
							// clear the durg edit field with an empty template drug
							/* ------------------------------------------------------- */
							drugTemplateEditorTableModel.reset();
							/* ------------------------------------------------------- */
							// clear the template model with an empty template prescription
							/* ------------------------------------------------------- */
							templateEditorModel.reset();
							/* ------------------------------------------------------- */
//							drugTemplateEditorTableModel.fireTableDataChanged();
							/* ------------------------------------------------------- */
							// reset the datafields
							/* ------------------------------------------------------- */
							TemplateControler.this.update(templateEditorModel.getType());
						}
						/* ============================================= */
					}
		};
		/* ------------------------------------------------------ */
		editorPanel.getSaveButton().setAction(saveAction);



//		 an action for the print button
		GECAMedAction closeAction = new GECAMedAction(null,
				"prescription.core.close",
				GECAMedModule.getSmallIcon(
						GECAMedIconNames.CLOSE),
				KeyEvent.VK_ESCAPE, // ?
				false, false, false) {

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

					/* (non-Javadoc)
					 * @see lu.tudor.santec.gecamed.core.gui.GECAMedAction#actionPerformed(java.awt.event.ActionEvent)
					 */
					@Override
					public void actionPerformed(ActionEvent p_Event) {
						/* ============================================= */
						// delete the marked templates
//						templateModel.deleteMarkedTemplates();

						editorPanel.setVisible(false);

						update(currentType);
						/* ============================================= */
					}
		};
		/* ------------------------------------------------------ */
		editorPanel.getCloseButton().setAction(closeAction);

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

	/**
	 * Checks the template
	 *
	 * @return
	 */
	private boolean checkTemplate(PrescriptionTemplate temp) {
		/* ====================================================== */
		StringBuffer msg = new StringBuffer();

		if (temp == null
				|| "".equals(temp.getDescription())
				|| temp.getDescription() == null) {
			msg.append(Translatrix.getTranslationString("template.desc.enterName"));
			// notify the user
			MainFrame.getInstance().showMessage(editorPanel, msg.toString());
			return false;
		}
		return true;
		/* ====================================================== */
	}


	/**
	 * Get the complete template from the editor
	 *
	 * @return
	 */
	private PrescriptionTemplate getCurrentTemplate() {
		/* ====================================================== */
//		 get the template
		PrescriptionTemplate template = templateEditorModel.getTemplate();
		/* ------------------------------------------------------ */
//		 set the type for the template
		// for that, we create a new EditorModel object, because it
		// has a static list of the PrescriptionType and the
		// appropriate method to obtain the right object
		EditorModel editorModel = new EditorModel(null);

		if (editorModel.getTypeForString(
				templateEditorModel.getType()) != null) {
			/* ------------------------------------------------------ */
				template.setPrescriptionTypeId(editorModel.getTypeForString(
						templateEditorModel.getType()).getId());
				/* ------------------------------------------------------ */
		} else {
			/* ------------------------------------------------------ */
			// without a type, we can not persist the template!!!!
			logger.error("Can not persist template without PrescriptionType. Aborting ....!");
			return null;
			/* ------------------------------------------------------ */
		}
		/* ------------------------------------------------------ */



		// get the prescription drugs from the
		// drugTableModel
		List<PrescriptionDrug> drugs = drugTemplateEditorTableModel.getAllDrugs();
		// as a TemplateDrug is nearly identical to the PrescriptionDrug
		// we just have to copy the drug to the templatedrug.
		// this is to keep the template drugs out of the drugs table.
		Set<TemplateDrug> templateDrugs = new HashSet<TemplateDrug>();
		if (drugs != null)
			for (PrescriptionDrug d : drugs) {
				/* ------------------------------------------------------ */
				// copy
				TemplateDrug td = drug2TemplateDrug(d);
				td.setTemplate(template);
				// add to the set
				templateDrugs.add(td);
				/* ------------------------------------------------------ */
			}
		template.setTemplateDrugs(templateDrugs);
		return template;
		/* ====================================================== */
	}

	/**
	 * Convert a PrescriptionDrug to a TemplateDrug
	 *
	 * @param d
	 * @return
	 */
	public static TemplateDrug drug2TemplateDrug(PrescriptionDrug d) {
		/* ====================================================== */
		TemplateDrug td = new TemplateDrug();
		td.setId(d.getId());
		td.setDrugId(d.getDrugId());
		td.setDrugListId(d.getDrugListId());
		td.setName(d.getName());
		td.setPosology(d.getPosology());

		return td;
		/* ====================================================== */
	}


	/**
	 * Convert a TemplateDrug to PrescriptionDrug
	 *
	 * @param t
	 * @return
	 */
	public static PrescriptionDrug templateDrug2Drug(TemplateDrug t) {
		/* ====================================================== */
		if (t != null) {
			PrescriptionDrug d = new PrescriptionDrug();
			d.setId(t.getId());
			d.setDrugId(t.getDrugId());
			d.setDrugListId(t.getDrugListId());
			d.setName(t.getName());
			d.setPosology(t.getPosology());

			return d;
		}
		return null;
		/* ====================================================== */
	}

	/* ***************************************************************
	 * End of Editor methods
	 * ***************************************************************
	 * ****************************************************************/





}
