package lu.tudor.santec.gecamed.esante.gui.history;

import java.awt.event.ActionEvent;
import java.util.Collection;
import java.util.HashMap;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.table.TableCellRenderer;

import lu.tudor.santec.gecamed.core.gui.GECAMedColors;
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.listener.IEntryPrintRenderer;
import lu.tudor.santec.gecamed.core.gui.listener.IEntryTypeHandler;
import lu.tudor.santec.gecamed.core.gui.widgets.GECAMedBaseDialogImpl;
import lu.tudor.santec.gecamed.core.utils.ManagerFactory;
import lu.tudor.santec.gecamed.esante.ejb.entity.beans.CdaDocument;
import lu.tudor.santec.gecamed.esante.ejb.session.beans.CDAManagerBean;
import lu.tudor.santec.gecamed.esante.ejb.session.interfaces.CDAManager;
import lu.tudor.santec.gecamed.esante.gui.dialogs.ESanteDialog;
import lu.tudor.santec.gecamed.esante.gui.tab.ESanteTab;
import lu.tudor.santec.gecamed.esante.gui.utils.ESanteGuiUtils;
import lu.tudor.santec.gecamed.esante.gui.worker.DocumentWorker;
import lu.tudor.santec.gecamed.esante.utils.ESanteUtils;
import lu.tudor.santec.gecamed.patient.ejb.entity.beans.IncidentEntry;
import lu.tudor.santec.gecamed.patient.ejb.session.beans.IncidentManagerBean;
import lu.tudor.santec.gecamed.patient.ejb.session.interfaces.IncidentManager;
import lu.tudor.santec.gecamed.patient.gui.PatientManagerModule;
import lu.tudor.santec.i18n.Translatrix;

import org.apache.log4j.Logger;

/**
 * @author jens.ferring(at)tudor.lu
 * 
 * @version
 * <br>$Log: CdaHistoryHandler.java,v $
 * <br>Revision 1.11  2014-02-17 14:04:31  ferring
 * <br>Editing file entries by clicking removed, context menu option to edit description and file name added instead
 * <br>
 * <br>Revision 1.10  2014-02-06 17:48:40  ferring
 * <br>flag added, to decide if the document shall be stored on the server or not
 * <br>
 * <br>Revision 1.9  2014-02-04 10:08:45  ferring
 * <br>eSante ID management completed
 * <br>Only those documents will be shown, that are retrieved by the RSQ
 * <br>
 * <br>Revision 1.8  2014-01-06 12:34:28  ferring
 * <br>download site constants moved
 * <br>
 * <br>Revision 1.7  2013-12-19 12:36:34  ferring
 * <br>GECAMedBaseDialogImpl.showMessage changed to ESanteDialog.showMessage
 * <br>
 * <br>Revision 1.6  2013-12-10 11:48:11  ferring
 * <br>delete CDA file when removing document entry and download site is client
 * <br>
 * <br>Revision 1.5  2013-12-06 16:25:29  ferring
 * <br>CDA synch fixed
 * <br>
 * <br>Revision 1.4  2013-11-26 10:30:17  ferring
 * <br>translated
 * <br>
 * <br>Revision 1.3  2013-11-22 14:51:16  ferring
 * <br>Restructured CDA tree and list notification, in order not to use an EntityBean as model.
 * <br>Buttons added to delete the CDA file and remove the incident entry
 * <br>
 * <br>Revision 1.2  2013-11-21 09:48:29  ferring
 * <br>refactored
 * <br>
 * <br>Revision 1.1  2013-10-08 08:54:13  ferring
 * <br>class name refactoring and tree view implementation (first steps)
 * <br>
 * <br>Revision 1.2  2013-09-30 11:53:49  ferring
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.1  2013-09-30 10:56:30  ferring
 * <br>eSante integration in GECAMed and synchronise funktion added
 * <br>
 */

public class CdaHistoryHandler implements IEntryTypeHandler
{
	/* ======================================== */
	// MEMBERS
	/* ======================================== */
	
	/** the logger Object for this class */
	private static Logger logger = Logger.getLogger(CdaHistoryHandler.class.getName());
	
	
	private ESanteTab			eSanteTab;
	
	private	CdaHistoryRenderer	renderer;
	
	private JPopupMenu			popup;
	
	private IncidentEntry		selectedEntry;		
	
	
	
	/* ======================================== */
	// CONSTRUCTOR
	/* ======================================== */
	
	public CdaHistoryHandler (ESanteTab tab)
	{
		this.eSanteTab	= tab;
		this.renderer	= new CdaHistoryRenderer();
	}
	
	
	
	/* ======================================== */
	// CLASS BODY
	/* ======================================== */
	
	public TableCellRenderer getRenderer (String entryType)
	{
		return renderer;
	}
	
	
	public boolean openEntry (IncidentEntry entry)
	{
		CdaDocument		document;
		Integer			entryId;
		
		
		if (entry == null || entry.getId() == null)
			return false;
		
		entryId		= entry.getId();
		document	= CDAManagerBean.getInstance().getDocument(entryId);
		
		if (document != null)
		{
			DocumentWorker.openDocument(
					document, 
					eSanteTab.getCdaHandler(),
					false);
			
			return true;
		}
		else
		{
			logger.info("There was no CDA document for the entry specified. " +
					"The entry " + entry.getId() + " will be deleted.");
			
			deleteEntry(findDocument(entry), entry, false);
			
			return false;
		}
	}
	
	
	public JPopupMenu getPopup (IncidentEntry entry)
	{
		if (popup == null)
		{
			JMenuItem	item;
			
			popup	= new JPopupMenu();
			popup.setOpaque(true);
			popup.setBackground(GECAMedColors.c_GECAMedBackground);
			
			item = new JMenuItem(new AbstractAction(
					Translatrix.getTranslationString("core.open"), 
					GECAMedModule.getSmallIcon(GECAMedIconNames.OPEN))
			{
				private static final long	serialVersionUID	= 1L;

				public void actionPerformed (ActionEvent e)
				{
					openEntry(selectedEntry);
				}
			});
			item.setOpaque(false);
			popup.add(item);
			
			item = new JMenuItem(new AbstractAction(
					Translatrix.getTranslationString("core.delete"), 
					GECAMedModule.getSmallIcon(GECAMedIconNames.REMOVE))
			{
				private static final long	serialVersionUID	= 1L;
				
				public void actionPerformed (ActionEvent e)
				{
					deleteEntry(findDocument(selectedEntry), selectedEntry, true);
				}
			});
			item.setOpaque(false);
			popup.add(item);
		}
		
		selectedEntry	= entry;
		
		return popup;
	}
	
	
	public HashMap<Integer, Object> getSpecialEntries (String entryType, Integer patientId)
	{
		return null;
	}
	
	
	public Collection<Action> getActions (IncidentEntry entry)
	{
		return null;
	}
	
	
	public IEntryPrintRenderer getPrintRenderer (String entryType)
	{
		return null;
	}
	
	
	public static void deleteEntryOfDocument (CdaDocument document)
	{
		if (document.getIncidentEntryId() != null)
		{
			try
			{
				deleteEntry(document, ManagerFactory.find(IncidentEntry.class, 
						document.getIncidentEntryId()), true);
			}
			catch (Exception e)
			{
				logger.error("Error while trying to delete CDA incident entry.", e);
			}
		}
	}
	
	
	
	/* ======================================== */
	// HELP METHODS
	/* ======================================== */
	
	private static void deleteEntry (CdaDocument document, IncidentEntry entry, boolean showConfirmationDialog)
	{
		Integer			entryId;
		CDAManager		cdaManager	= CDAManagerBean.getInstance();
		IncidentManager	iManager	= (IncidentManager) ManagerFactory.getRemote(IncidentManagerBean.class);
		ESanteTab		eSanteTab;
		
		
		if (entry == null || entry.getId() == null)
			return;
		
		entryId		= entry.getId();
//		document	= cdaManager.getDocument(entryId);
		
		if (document != null)
		{
			if (showConfirmationDialog)
			{
				// show a confirmation dialog
				int option = ESanteDialog.showMessageDialog(
						MainFrame.getInstance(), 
						Translatrix.getTranslationString("esante.CdaHistoryHandler.deleteEntryWarningTitle"), 
						Translatrix.getTranslationString("esante.CdaHistoryHandler.deleteEntryWarning"), 
						GECAMedBaseDialogImpl.YES_NO_BUTTON_MODE);
				if (option != GECAMedBaseDialogImpl.YES_OPTION)
					return;
			}
			
			
			Integer patientId	= entry.getIncident().getPatientId();
			String	docId		= document.getDocumentUniqueId();
			
			document.setIncidentEntryId(null);
			if (document.isPersistent())
				document	= cdaManager.updateCdaDocument(document,
						ESanteUtils.getCdaDownloadSite() == ESanteUtils.CDA_DOWNLOAD_SITE_SERVER);
			
			if (ESanteUtils.getCdaDownloadSite() == ESanteUtils.CDA_DOWNLOAD_SITE_CLIENT)
			{
				document = cdaManager.deleteCdaFile(document);
			}
			
			ESanteGuiUtils.trace("Documents", "CDA document \"" + docId + "\" (incident entry " + entryId 
					+ ") removed from GECAMed history of patient " + patientId);
			eSanteTab	= ESanteTab.getESanteTab(patientId);
			eSanteTab.fireDocumentChanged(document);
		}
		else
		{
			// there is no CDA document of this incident entry
			// don't ask, just delete it
			logger.info("There was no CDA document for the entry " + entryId);
		}
		
		iManager.removeIncidentEntry(entry);
		PatientManagerModule.getInstance().getPatientPanel().incidentEntryDeleted(entry);
		PatientManagerModule.getInstance().getPatientPanel().reloadHistory();
	}
	
	
	private CdaDocument findDocument (IncidentEntry entry)
	{
		ESanteTab eSanteTab = ESanteTab.getESanteTab(entry.getIncident().getPatientId());
		
		return eSanteTab.getCdaHandler().getDocumentWithEntryId(entry.getId());
	}
}
