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

import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.List;

import javax.swing.DefaultListModel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.SwingUtilities;

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.utils.ManagerFactory;
import lu.tudor.santec.gecamed.patient.ejb.entity.beans.Incident;
import lu.tudor.santec.gecamed.patient.ejb.entity.beans.Patient;
import lu.tudor.santec.gecamed.prescription.ejb.entity.beans.Prescription;
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.util.PrescriptionPrinter;
import lu.tudor.santec.gecamed.prescription.gui.widgets.editor.EditorControler;
import lu.tudor.santec.gecamed.prescription.gui.widgets.editor.EditorModel;
import lu.tudor.santec.gecamed.prescription.gui.widgets.editor.PrescriptionTab;

/**
 * This is the controler class for the AntecedentPanel.
 * It initializes the list model, gets the data from the database and is responsible
 * for any further interactions.
 * The list has a right-click context menu with the actions to print, print copy, represcribe and edit.
 * The actions are piped to the EditorControler of the prescription editor.
 * 
 * @author martin.heinemann@tudor.lu
 *
 *
 * @version
 * <br>$Log: AntecedentPrescriptionControler.java,v $
 * <br>Revision 1.4  2010-03-30 10:39:04  troth
 * <br>Redesign of the prescription view - change icon manager class
 * <br>
 * <br>Revision 1.3  2008-10-09 12:06:49  heinemann
 * <br>http://santec.tudor.lu/trac/gecamed/ticket/199
 * <br>
 * <br>Revision 1.2  2008-09-25 09:43:08  heinemann
 * <br>fixed copyrights
 * <br>
 * <br>Revision 1.1  2008-07-23 15:13:57  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.7  2008-01-15 13:40:35  heinemann
 * <br>better documentation
 * <br>
 * <br>Revision 1.6  2007-11-20 08:58:53  hermen
 * <br>moved Managerfactory to core.utils and refactured code to use ManagerFactory instead of context.lookup
 * <br>
 * <br>Revision 1.5  2007/06/18 11:31:36  hermen
 * <br>cleanup of old stuff and moved some beans
 * <br>
 * <br>Revision 1.4  2007/03/13 08:23:15  heinemann
 * <br>fixed right click
 * <br>
 * <br>Revision 1.3  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.2  2007/03/02 08:28:44  hermen
 * <br>initial checkin after the merge of PatientModuleRebuild with the main HEAD
 * <br>
 * <br>Revision 1.1.2.9  2007/02/21 10:00:40  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.1.2.8  2007/01/22 14:42:20  heinemann
 * <br>Complete - # 6: Antecedent prescription viewer
 * <br>http://santec.tudor.lu:8888/gecamed/ticket/6
 * <br>
 * <br>Revision 1.1.2.7  2007/01/22 10:24:07  heinemann
 * <br>Incomplete - # 13: print copies of prescriptions
 * <br>http://santec.tudor.lu:8888/gecamed/ticket/13
 * <br>
 * <br>Revision 1.1.2.6  2007/01/19 12:44:17  heinemann
 * <br>Complete - # 28: Accident Nr and date must appear on the prescription printout
 * <br>http://santec.tudor.lu:8888/gecamed/ticket/28
 * <br>
 * <br>Revision 1.1.2.5  2007/01/12 13:04:06  heinemann
 * <br>Incomplete - # 51: Create preview for prescription templates
 * <br>http://santec.tudor.lu:8888/gecamed/ticket/51
 * <br>Incomplete - # 21: Context Menu -> create new prescription
 * <br>http://santec.tudor.lu:8888/gecamed/ticket/21
 * <br>
 * <br>Revision 1.1.2.4  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.3  2006/12/28 10:32:26  heinemann
 * <br>bug fixing and template improvements
 * <br>
 * <br>Revision 1.1.2.2  2006/12/22 13:18:09  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.1.2.1  2006/12/14 09:34:01  heinemann
 * <br>many changes
 * <br>
 */
public class AntecedentPrescriptionControler {


	private AntecedentPanel panel;
	private Patient currentPatient;
	private String type;
	private DefaultListModel listModel;
//	private Incident incident;
	private PrescriptionTab tab;

	/**
	 * Needs the current tab in which it is going to be integrated.
	 * 
	 * @param tab
	 */
	public AntecedentPrescriptionControler(PrescriptionTab tab) {
		/* ====================================================== */
		// create a panel
		this.panel = new AntecedentPanel();
		this.tab = tab;

		this.listModel = new DefaultListModel();
		panel.getList().setModel(listModel);


		// init the mouse and key listeners for the list
		initListListener();
		initPopupActions();
		/* ====================================================== */
	}


	/**
	 * @return
	 */
	public JPanel getPanel() {
		/* ============================================= */
		return panel;
		/* ============================================= */
	}

	/**
	 * Switch the prescription type. Will do an update on the list itself.
	 * 
	 * @param type
	 */
	public void switchType(String type) {
		/* ============================================= */
		this.type = type;
		updateListData();
		/* ============================================= */
	}

	/**
	 * Set the new patient. Will do an update on the list itself.
	 * 
	 * @param currentPatient
	 */
	public void setPatient(Patient currentPatient) {
		/* ============================================= */
		this.currentPatient = currentPatient;
		// fill the list with the current patient's data
		updateListData();
		/* ============================================= */
	}

	/**
	 * Update the list and set the current incident id to the model
	 *
	 * @param incident
	 */
	public void updateListData(Incident incident) {
		/* ====================================================== */
		panel.setIncidentId(incident.getId());
//		this.incident = incident;
		this.updateListData();
		/* ====================================================== */
	}

	/**
	 * update the list data
	 */
	public void updateListData() {
		/* ====================================================== */
		EditorModel editorModel = new EditorModel(null);

		Integer pId = null;
		Integer tId = null;
		try {
			pId = currentPatient.getId();
//			pId = PatientManagerModule.getCurrentPatient().getId();
			tId = editorModel.getTypeForString(type).getId();
		} catch (Exception e) {
			// TODO: handle exception
		}
		// get the "old" prescriptions from the server
		List<Prescription> data = getManager().getAntecedentPrescriptions(
				pId, tId);
		if (data != null) {
			/* ------------------------------------------------------ */
			// clear the model
			listModel.clear();

			// set the new data
			for (Prescription p : data)
				listModel.addElement(p);
			/* ------------------------------------------------------ */
		}
		/* ====================================================== */
	}




	/**
	 * Init the mouse and key listeners for the JList
	 */
	private void initListListener() {
		/* ============================================= */
		final JList list = panel.getList();
		list.addMouseListener(new MouseAdapter() {

			/* (non-Javadoc)
			 * @see java.awt.event.MouseAdapter#mouseClicked(java.awt.event.MouseEvent)
			 */
			@Override
			public void mouseReleased(MouseEvent e) {
				/* ============================================= */
				showPreview(e);
				openPopup(e);
				/* ============================================= */
			}

			/* (non-Javadoc)
			 * @see java.awt.event.MouseAdapter#mousePressed(java.awt.event.MouseEvent)
			 */
			@Override
			public void mousePressed(MouseEvent e) {
				/* ============================================= */
//				showPreview(e);
				int row = list.locationToIndex(e.getPoint());
				list.setSelectedIndex(row);
				openPopup(e);
				/* ============================================= */
			}


			private void openPopup(MouseEvent e) {
				/* ====================================================== */
				if (e.isPopupTrigger()) {
					panel.getPopup().show(panel.getList(), e.getX(), e.getY());
				}
				/* ====================================================== */
			}

			private void showPreview(MouseEvent e) {
				/* ====================================================== */
				if (SwingUtilities.isLeftMouseButton(e))
					if (e.getClickCount() == 2) {
						int row = list.locationToIndex(e.getPoint());
						try {
							/* ------------------------------------------------------ */
							// get the prescription
							PrescriptionPrinter.showPrescription((Prescription) listModel.getElementAt(row));
							/* ------------------------------------------------------ */
						} catch (Exception e2) {
							e2.printStackTrace();
						}
					}
					else {
						// show quick preview
						try {
						panel.showQuickPreview((Prescription) list.getSelectedValues()[0], e);
						} catch (Exception e1) {
						}
					}
				/* ====================================================== */
			}



		});


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


	/**
	 * init the actions for the context menu
	 */
	private void initPopupActions() {
		/* ====================================================== */
		GECAMedAction printCopyAction = new GECAMedAction(
				null,
				"prescription.buttons.printCopy",
				PrescriptionIcons.getSmallIcon(PrescriptionIcons.COPY),
				KeyEvent.VK_C,
				false, false, false) {
			private static final long serialVersionUID = 1L;
			@Override
			public void actionPerformed(ActionEvent evt) {
				/* ====================================================== */
				EditorControler.printCopy((Prescription) panel.getList().getSelectedValue());
				/* ====================================================== */
			}
		};
		/* ------------------------------------------------------ */
		/* ------------------------------------------------------ */
		GECAMedAction printAction = new GECAMedAction(
				null,
				"prescription.buttons.print",
				PrescriptionIcons.getSmallIcon(PrescriptionIcons.PRINT),
				KeyEvent.VK_P,
				false, false, false) {
			private static final long serialVersionUID = 1L;
			@Override
			public void actionPerformed(ActionEvent evt) {
				/* ====================================================== */
				EditorControler.doPrint((Prescription) panel.getList().getSelectedValue());
				/* ====================================================== */
			}
		};

		/* ------------------------------------------------------ */
		/* ------------------------------------------------------ */
		GECAMedAction represcribeAction = new GECAMedAction(
				null,
				"prescription.buttons.represcribe",
				PrescriptionIcons.getSmallIcon(PrescriptionIcons.REPRESCRIBE),
				KeyEvent.VK_R,
				false, false, false) {
			private static final long serialVersionUID = 1L;
			@Override
			public void actionPerformed(ActionEvent evt) {
				/* ====================================================== */
				tab.editorControler.represcribe(panel.getList().getSelectedValues());
				/* ====================================================== */
			}
		};
		/* ------------------------------------------------------ */
		/* ------------------------------------------------------ */
		GECAMedAction editAction = new GECAMedAction(
				null,
				"prescription.buttons.edit",
				GECAMedModule.getSmallIcon(GECAMedIconNames.EDIT),
				KeyEvent.VK_E,
				false, false, false) {
			private static final long serialVersionUID = 1L;
			@Override
			public void actionPerformed(ActionEvent evt) {
				/* ====================================================== */
				tab.editorControler.modifyPrescription(panel.getList().getSelectedValues());
				/* ====================================================== */
			}
		};

		panel.getPopup().add(printCopyAction);
		panel.getPopup().add(new JSeparator());
		panel.getPopup().add(printAction);
		panel.getPopup().add(new JSeparator());
		panel.getPopup().add(represcribeAction);
		panel.getPopup().add(new JSeparator());
		panel.getPopup().add(editAction);
		/* ====================================================== */
	}


	/**
	 * Get an instance of the prescription manager session bean
	 *
	 * @return
	 */
	protected static PrescriptionManager getManager() {
		/* ====================================================== */
		return (PrescriptionManager)
			ManagerFactory.getRemote(PrescriptionManagerBean.class);
		/* ====================================================== */
	}



}
