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

import java.awt.Component;
import java.awt.event.ActionEvent;

import javax.swing.JComponent;
import javax.swing.JPopupMenu;

import org.apache.log4j.Logger;

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.AEntryAction;
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.entity.beans.Dsp;
import lu.tudor.santec.gecamed.esante.ejb.session.beans.CDAManagerBean;
import lu.tudor.santec.gecamed.esante.gui.IconNames;
import lu.tudor.santec.gecamed.esante.gui.dialogs.ESanteDialog;
import lu.tudor.santec.gecamed.esante.gui.utils.ESanteGuiUtils;
import lu.tudor.santec.gecamed.esante.gui.webservice.SoapSender;
import lu.tudor.santec.gecamed.esante.gui.webservice.UploadDoc;
import lu.tudor.santec.gecamed.esante.gui.webservice.WebserviceConstants;
import lu.tudor.santec.gecamed.esante.gui.webservice.XDS;
import lu.tudor.santec.gecamed.patient.ejb.entity.beans.IncidentEntry;
import lu.tudor.santec.gecamed.patient.ejb.entity.beans.Patient;
import lu.tudor.santec.gecamed.patient.ejb.session.beans.IncidentManagerBean;
import lu.tudor.santec.gecamed.patient.ejb.session.interfaces.IncidentManager;
import lu.tudor.santec.i18n.Translatrix;

/**
 * 
 * @author donak
 *
 * @version <br>
 *          $Log: UploadToDspAction.java,v $ Revision 1.13 2014-01-30 18:14:12 donak upload option will only be offered, if the user possesses the appropriate
 *          mandate and access rights to the dsp.
 *
 *          Revision 1.12 2013-11-20 10:30:18 ferring import removed
 *
 *          Revision 1.11 2013-10-17 14:54:30 donak Corrected upload handler for letters Defined incident entry dependent presets for upload metadata Bug fixing
 *          and documentation
 *
 */
public class UploadToDspAction extends AEntryAction {

	private static final long serialVersionUID = 1L;

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

	private int uploadMode = WebserviceConstants.UPLOAD_INITIALE_UPLOAD;

	private IncidentEntry entry2Upload;
	// stores the metadata and unique id of the document (if the document is already present at the EHR)
	private CdaDocument documentMetadata = null;

	protected static IncidentManager iManager = (IncidentManager) ManagerFactory.getRemote(IncidentManagerBean.class);

	private SoapSender sender = new SoapSender(null, true);

	public UploadToDspAction() {
		super(Translatrix.getTranslationString("esante.actions.upload"), ESanteGuiUtils.getIcon(IconNames.UPLOAD_TO_DSP, GECAMedIconNames.SMALLPIX));
	}

	public UploadToDspAction(String text) {
		super(text, ESanteGuiUtils.getIcon(IconNames.UPLOAD_TO_DSP, GECAMedIconNames.SMALLPIX));
	}

	/**
	 * Defines the incident entry that should be treated. The treatment might either be to upload a new incident entry to the EHR, to upload a new version to
	 * the EHR, or to change its metadata at the EHR.
	 */
	public void setEntry(IncidentEntry entry) {
		this.entry2Upload = entry;
	}

	/**
	 * Sets the metadata of the document that should be treated
	 * 
	 * @param documentMetadata
	 *            The metadata of the document
	 */
	public void setMetadata(CdaDocument documentMetadata) {
		this.documentMetadata = documentMetadata;
	}

	/**
	 * Upload mode must only be set if a former version of the document already exists in the EHR.
	 * 
	 * @param uploadMode
	 *            Set the upload mode for the next event. The following possibilities exist:<br/>
	 * <br/>
	 *            <ul>
	 *            <li>{@link WebserviceConstants#UPLOAD_UPDATE_METADATA UPLOAD_UPDATE_METADATA}</li>
	 *            <li>{@link WebserviceConstants#UPLOAD_REPLACE_DOCUMENT UPLOAD_REPLACE_DOCUMENT}</li>
	 *            <li>{@link WebserviceConstants#UPLOAD_INITIALE_UPLOAD UPLOAD_UPDATE_BOTH}</li>
	 *            </ul>
	 */
	public void setUploadMode(int uploadMode) {
		this.uploadMode = uploadMode;
	}

	public void actionPerformed(final ActionEvent actionEvent) {

		if (this.uploadMode != WebserviceConstants.UPLOAD_INITIALE_UPLOAD) {

			Patient patient = GECAMedModule.getCurrentPatient();
			Dsp uploadDsp = CDAManagerBean.getInstance().getLinkedDsp(patient.getId());

			try {
				// set the dsp
				sender.setDsp(uploadDsp);
				// set the id of the document, that should be uploaded
				sender.setDocumentUniqueId(this.entry2Upload.getCdaUniqueId());
				CdaDocument latestVersionMetadata = null;

				// retrieve the metadata of the latest version of the document
				latestVersionMetadata = XDS.retrieveLatestVersionMetaData(sender);
				this.setMetadata(latestVersionMetadata);
			} catch (Exception e1) {
				// There is no cda document for the unique document id that has been assigned to the incident entry. This means neither on the EHR of the
				// patient nor in the local database a cda corresponding to this id could be found.

				// Thus indicate this to the user
				ESanteDialog.showMessageDialog(
						MainFrame.getInstance(),
						Translatrix.getTranslationString("esante.exceptions.cdaNotExistant.title"),
						Translatrix.getTranslationString("esante.exceptions.cdaNotExistant.message", new String[] { this.entry2Upload.getCdaUniqueId(),
								uploadDsp.getDspOid(), patient.getFirstName() + " " + patient.getSurName() }), ESanteDialog.OK_BUTTON_MODE,
						GECAMedModule.getScaledIcon(GECAMedIconNames.WARNING, 32));
				logger.error("Error while trying to obtain document meta data.\n" + e1);
				// remove the invalid unique document id from the incident entry
				this.entry2Upload.setCdaUniqueId(null);
				// and remove the item from the popup (not sure if this is needed)
				Component source = ((JPopupMenu) ((JComponent) actionEvent.getSource()).getParent()).getInvoker();
				source.repaint();

				// stop processing (a better workflow might be to upload the document to the dsp - like an initial upload)
				return;
			}
		}

		XDS.initiateUpload(actionEvent, this.entry2Upload, this.documentMetadata, this.uploadMode);
	}
}