/*******************************************************************************
 * 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.letter.gui.actions;

import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.Vector;

import javax.swing.JComponent;
import javax.swing.JOptionPane;

import lu.tudor.santec.gecamed.addressbook.ejb.entity.beans.Contact;
import lu.tudor.santec.gecamed.core.gui.GECAMedModule;
import lu.tudor.santec.gecamed.core.gui.MainFrame;
import lu.tudor.santec.gecamed.core.gui.controller.ControllerConfig;
import lu.tudor.santec.gecamed.core.gui.controller.document.DocumentController;
import lu.tudor.santec.gecamed.core.gui.controller.document.word.WordController;
import lu.tudor.santec.gecamed.core.gui.controller.document.writer.WriterController;
import lu.tudor.santec.gecamed.core.utils.ManagerFactory;
import lu.tudor.santec.gecamed.letter.ejb.entity.beans.Letter;
import lu.tudor.santec.gecamed.letter.ejb.entity.beans.LetterTemplate;
import lu.tudor.santec.gecamed.letter.ejb.session.beans.LetterBean;
import lu.tudor.santec.gecamed.letter.ejb.session.beans.LetterTemplateBean;
import lu.tudor.santec.gecamed.letter.ejb.session.interfaces.LetterInterface;
import lu.tudor.santec.gecamed.letter.ejb.session.interfaces.LetterTemplateInterface;
import lu.tudor.santec.gecamed.letter.gui.LetterTemplateModule;
import lu.tudor.santec.gecamed.letter.gui.settings.LetterTemplateSettings;
import lu.tudor.santec.gecamed.patient.ejb.entity.beans.Incident;
import lu.tudor.santec.gecamed.patient.ejb.entity.beans.IncidentEntry;
import lu.tudor.santec.gecamed.patient.ejb.entity.beans.IncidentEntryType;
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.Level;
import org.apache.log4j.Logger;

/**
 * Class to create a new letter from a LetterTemplate. This is not a GECAMedAction!!!
 * 
 * @author martin.heinemann@tudor.lu
 * 03.09.2008
 * 10:49:25
 *
 *
 * @version
 * <br>$Log: CreateLetterAction.java,v $
 * <br>Revision 1.17  2013-12-27 18:09:24  donak
 * <br>Cleanup of imports
 * <br>
 * <br>Revision 1.16  2013-07-15 06:18:35  ferring
 * <br>logging changed
 * <br>
 * <br>Revision 1.15  2013-05-02 08:55:31  ferring
 * <br>letters aren't overwritten anymore.
 * <br>Letters where lost, when opening another patient or closing current patient and then closing the letter.
 * <br>
 * <br>Revision 1.14  2013-02-14 08:15:18  ferring
 * <br>incident selection added to new letters and improved for files
 * <br>
 * <br>Revision 1.13  2013-02-05 13:15:18  ferring
 * <br>letter status added
 * <br>
 * <br>Revision 1.12  2012-12-14 09:48:21  ferring
 * <br>Interface IController replaced by abstract class DocumentController
 * <br>Function added to update placeholders in letter template
 * <br>
 * <br>Revision 1.11  2012-11-26 07:56:14  ferring
 * <br>New placeholders are introduced to the letter module
 * <br>The replacement algorithm in Word- and WriterCotnroller has been changed
 * <br>Multicontacts are prepared, but not yet implemented
 * <br>
 * <br>Revision 1.10  2011-08-17 08:41:16  ferring
 * <br>Office controller moved to core as they are not only used by the letter module anymore.
 * <br>
 * <br>Revision 1.9  2011-07-20 09:25:19  hermen
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.8  2011-07-20 08:31:05  hermen
 * <br>fixed logging to logfiles
 * <br>
 * <br>Revision 1.7  2010-09-23 12:22:03  hermen
 * <br>now sets current user as creator of incident entry instead of current phy, which was wrong!!!
 * <br>
 * <br>http://santec.tudor.lu/trac/gecamed/ticket/643
 * <br>
 * <br>Revision 1.6  2009-12-16 11:12:15  hermen
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.5  2009-02-25 13:26:09  hermen
 * <br>added siteID to incidents and invoices
 * <br>
 * <br>Revision 1.4  2008-12-10 13:15:40  hermen
 * <br>added logging
 * <br>
 * <br>Revision 1.3  2008-09-25 09:43:07  heinemann
 * <br>fixed copyrights
 * <br>
 * <br>Revision 1.2  2008-09-05 14:17:07  heinemann
 * <br>Fixed placeholders spelling.
 * <br>Fixed problem with placeholders that owns some trailing whitespaces. Replacing works now. In Oo. Word not tested!!!
 * <br>
 * <br>Revision 1.1  2008-09-03 10:24:14  heinemann
 * <br>*** empty log message ***
 * <br>
 *   
 */
public class CreateLetterAction {
    
    	/**
	 * static logger for this class
	 */
	private static Logger logger = Logger
		.getLogger(CreateLetterAction.class.getName());

//	private Map<String, String> data;

	private Object type;

	private LetterTemplate template;
	
	private Incident incident;

	private List<Contact> contacts;

	private String name;

	private JComponent parentComponent;
	
	/**
	 * 
	 */
	public CreateLetterAction(LetterTemplate template, List<Contact> contacts, String name, JComponent parentComponent, Incident attachToIncident) {
		/* ================================================== */
		this.template = template;
		this.contacts  = contacts;
		this.name = name;
		this.parentComponent = parentComponent;
		this.incident = attachToIncident;
		/* ================================================== */
	}
	
	
	
	
	public void create() 
	{
		final Integer patientId		= GECAMedModule.getCurrentPatient().getId();
		final Integer physicianId	= GECAMedModule.getCurrentPhysician().getId();
		final Integer userId		= GECAMedModule.getCurrentUser().getId();
		
		
		/* ================================================== */
		// New Thread, routine to open the text processing software,
		// loading the
		// template and saving it with the given name,
		// or with its filename on the server. Similar to :
		// AddTemplateDialog
//		data = PlaceholdersConfig.getPlaceholdersMap(contact, 1);
		Thread t = new Thread() {
			
			public void run() {
				/* ================================================== */
				MainFrame.getInstance().setWaitCursor(true);
				
				
				/* ------------------------------------------------------- */
				// Initiate text processing controller
				/* ------------------------------------------------------- */
				DocumentController controller = LetterTemplateModule.getController();
				if (controller == null) {
				    logger.info("ControllerConfig.getController() returns NULL....stopping here");
				    MainFrame.getInstance().setWaitCursor(false);
				    return;
				}
				try {
					/* ------------------------------------------------------- */
					// Getting the manager to receive the template
					// from
					// the server
					/* ------------------------------------------------------- */
					LetterTemplateInterface manager = (LetterTemplateInterface) ManagerFactory
									.getRemote(LetterTemplateBean.class);
					/* ------------------------------------------------------- */
					// read the data
					/* ------------------------------------------------------- */
					byte[] filebytes = null;
					try {
						// Get the bytes of the template
						filebytes = LetterTemplateModule.getInstance()
								.getManager().getTemplateBinary(
									template);
					} catch (Exception e) {
					    	logger.log(Level.WARN, "Error loading template File ", e);
					    
						JOptionPane.showMessageDialog(
										LetterTemplateModule.getInstance().getContentPane(),
										Translatrix.getTranslationString("LetterTemplateModule.dialog.error.outofsync") + "\n" +
										LetterTemplateModule.getInstance().getManager().getServerTemplateDir() + File.separator + 
										template.getGeneratedFileName()	,
										Translatrix.getTranslationString("LetterTemplateModule.dialog.error.title"),
										JOptionPane.ERROR_MESSAGE);
						MainFrame.getInstance().setWaitCursor(false);
					}
					/* ------------------------------------------------------- */
					// Giving the template to the controller, in
					// order to open
					// it in the text processing software
					/* ------------------------------------------------------- */
					if (!ControllerConfig.getLocalLetterPath().equalsIgnoreCase(
									LetterTemplateSettings.DEFAULT)) {
						/* ------------------------------------------------------- */
						controller.setDocument(filebytes,ControllerConfig.getLocalLetterPath());
						/* ------------------------------------------------------- */
					}
					else {
						/* ------------------------------------------------------- */
						controller.setDocument(filebytes);
						/* ------------------------------------------------------- */
					}
					/* ------------------------------------------------------- */
					// open the file for edit
					/* ------------------------------------------------------- */
					controller.open(DocumentController.TYPE_NEW_LETTER);
					/* ------------------------------------------------------- */
					// replace the placeholders with the data
					/* ------------------------------------------------------- */
					controller.startReplacing(template.getPlaceholderVersion(), contacts);
					/* ------------------------------------------------------- */
					MainFrame.getInstance().setWaitCursor(false);
					controller.waitForUserInput();
					lu.tudor.santec.gecamed.core.gui.controller.data.State state = controller.getState();
					/* ------------------------------------------------------- */
					// If the user saved the document, a new
					// IncidentEntry is
					// created as LetterType.
					// The document is saved in the patients history
					/* ------------------------------------------------------- */
					if (state.isSaved()) {
						/* ------------------------------------------------------- */
						// Getting document from the client
						/* ------------------------------------------------------- */
						File document = controller.getDocumentbyFile();
						String filename = document.getName();
						/* ------------------------------------------------------- */
						// Saving the file on the server
						/* ------------------------------------------------------- */
						String generated_filename = manager.saveFile(
							controller.getDocument(),
							document.getName(),
							patientId);
						/* ------------------------------------------------------- */
						if (ControllerConfig.deleteDocuments()) {
							// Delete the local document
							controller.deleteDocument();
						}
						/* ------------------------------------------------------- */
						// Creating the incident for the patient
						/* ------------------------------------------------------- */
						IncidentManager iManager = (IncidentManager) ManagerFactory
													.getRemote(IncidentManagerBean.class);

						IncidentEntry ie = new IncidentEntry();

						IncidentEntryType entryType = new IncidentEntryType();
						entryType.setName(IncidentManager.LETTER);
						/* ------------------------------------------------------- */
						// Attaching the Type of the file to the
						// incident
						/* ------------------------------------------------------- */
						ie.setEntryType(entryType);
						/* ------------------------------------------------------- */
						// Create a new incident if the current is
						// not present.
						/* ------------------------------------------------------- */
						if (incident == null)
						{
							incident = new Incident(patientId, physicianId);
							incident.setSiteId(MainFrame.getCurrentSiteId());
							incident = iManager.saveIncident(incident);
						}
						ie.setIncident(incident);
						/* ------------------------------------------------------- */
						// Set created, createdby, modified,
						// modifiedby
						/* ------------------------------------------------------- */
						ie.setCreated(new Date());
						ie.setCreatedBy(userId);
						ie.setModified(new Date());
						ie.setModifiedBy(userId);
						/* ------------------------------------------------------- */
						// Set the file name
						/* ------------------------------------------------------- */
						if (name == null || "".equals(name.trim())) {
							/* ------------------------------------------------------- */
							ie.setFileName(filename);
							/* ------------------------------------------------------- */
						} else {
							/* ------------------------------------------------------- */
							ie.setFileName(name);
							/* ------------------------------------------------------- */
						}
						ie.setTextContent(name);
						ie.setFileSize(document.length());
						/* ------------------------------------------------------- */
						// save
						/* ------------------------------------------------------- */
						ie.setOriginalFilename(generated_filename);
						Vector<String> statuses = LetterTemplateModule.getInstance().getLetterStatuses();
						if (statuses != null 
								&& statuses.size() > 0 
								&& statuses.get(0) != null
								&& statuses.get(0).trim().length() > 0)
						{
							ie.setStatus(statuses.get(0));
						}
						ie = iManager.saveEntry(ie, IncidentManager.LETTER);
						/* ------------------------------------------------------- */
						// Saving letter corresponding to the
						// incident entry
						/* ------------------------------------------------------- */
						int incedentEntryId = ie.getId();
	
						LetterInterface letterManager = (LetterInterface) ManagerFactory
																.getRemote(LetterBean.class);
						/* ------------------------------------------------------- */
						Letter letter = new Letter();
						letter.setIncidentEntryID(incedentEntryId);
						if (controller instanceof WordController) {
							/* ------------------------------------------------------- */
							letter.setMimetype(ControllerConfig.MIME_WORD);
							/* ------------------------------------------------------- */
						}
						if (controller instanceof WriterController) {
							/* ------------------------------------------------------- */
							letter.setMimetype(ControllerConfig.MIME_WRITER);
							/* ------------------------------------------------------- */
						}
						type = template.getType();
						letter.setType((String) type);

						letterManager.addLetter(letter);

//						LetterPanel.getInstance().getCbModel().queryLetterTypes();
						/* ------------------------------------------------------- */
					} else {
					    logger.info("file was not saved, not writing file to DB");
						/* ------------------------------------------------------- */
						if (ControllerConfig.deleteDocuments()) {
							// Delete the local document
							controller.deleteDocument();
							logger.info("deleting temp file");
						}
						/* ------------------------------------------------------- */
					}
					/* ------------------------------------------------------- */
					// reload the patient history
					/* ------------------------------------------------------- */
					PatientManagerModule.getInstance().getPatientPanel().reloadHistory();
					/* ------------------------------------------------------- */
				} catch (Throwable e) {
					/* ------------------------------------------------------- */
					logger.log(Level.WARN, "Error creating letter: ", e);
					e.printStackTrace();
					MainFrame.getInstance().setWaitCursor(false);
					JOptionPane.showMessageDialog(
									parentComponent,
									Translatrix.getTranslationString("LetterTemplateModule.dialog.error.letteropening") + "\n" + 
									e.getLocalizedMessage(),
									Translatrix.getTranslationString("LetterTemplateModule.dialog.error.title"),
									JOptionPane.ERROR_MESSAGE);
					/* ------------------------------------------------------- */
				}
			}
		};
		t.start();
		/* ================================================== */
	}
	
}
