/*******************************************************************************
 * 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.awt.Component;
import java.io.File;
import java.util.Date;
import java.util.Vector;

import javax.swing.JOptionPane;

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.core.utils.controller.utils.FileUtils;
import lu.tudor.santec.gecamed.letter.ejb.entity.beans.LetterPlaceholder;
import lu.tudor.santec.gecamed.letter.ejb.entity.beans.LetterTemplate;
import lu.tudor.santec.gecamed.letter.ejb.session.beans.LetterTemplateBean;
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.i18n.Translatrix;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;

/**
 * Creates a new letter template. This is not a GECAMedAction!!
 * 
 * 
 * @author martin.heinemann@tudor.lu
 * 27.08.2008
 * 15:06:52
 *
 *
 * @version
 * <br>$Log: CreateTemplateAction.java,v $
 * <br>Revision 1.14  2013-12-27 18:09:24  donak
 * <br>Cleanup of imports
 * <br>
 * <br>Revision 1.13  2013-07-15 06:18:35  ferring
 * <br>logging changed
 * <br>
 * <br>Revision 1.12  2013-01-14 07:59:55  ferring
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.11  2013-01-09 11:12:00  ferring
 * <br>insert renamed to append and will now add the text at the end of the document
 * <br>
 * <br>Revision 1.10  2013-01-07 13:28:23  ferring
 * <br>Type filter in letter template list shows now only those templates types, that of which exists templates that are available for the physician.
 * <br>Type chooser of the meta data shows now all template types with existing templates, independent of the current physician and of the types that exist for existing letters.
 * <br>
 * <br>Revision 1.9  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.8  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.7  2012-03-15 10:05:23  ferring
 * <br>Whether the template requires contact information is checked automatically everytime the document is saved or created
 * <br>
 * <br>Revision 1.6  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.5  2009-12-16 11:12:15  hermen
 * <br>*** empty log message ***
 * <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-03 10:24:14  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.1  2008-08-27 15:34:53  heinemann
 * <br>*** empty log message ***
 * <br>
 *   
 */
public class CreateTemplateAction {
	
	
	private Vector<LetterPlaceholder> placeHolders;
	private File importFile;
	private String templatename;
	private String templateType;
	private Component parentPanel;
	private String addressType;
	
	/**
	 * static logger for this class
	 */
	private static Logger logger = Logger
		.getLogger(CreateTemplateAction.class.getName());
	
	
	/**
	 * @param placeHolders
	 * @param type
	 * @param importFile
	 * @param name
	 * @param parent
	 */
	public CreateTemplateAction(Vector<LetterPlaceholder> placeHolders, String type, File importFile, String name, String addressType, Component parent) {
		/* ================================================== */
		this.placeHolders = placeHolders;
		this.templateType = type;
		this.importFile   = importFile;
		this.templatename = name;
		this.addressType  = addressType;
		this.parentPanel  = parent;
		/* ================================================== */
	}
	
	
	public void create() {
		/* ================================================== */
		// New Thread that creates a new file on the disk of the client, opens
		// it and when it's saved
		// the Thread will store it in the database. Similar to :
		// CreateLetterListener
		/* ------------------------------------------------------- */
		// build the placeholder string that is inserted in the document
		/* ------------------------------------------------------- */
		final StringBuffer insertPlaceholders = new StringBuffer();
		
		for (LetterPlaceholder s : this.placeHolders) 
		{
			if (s != null && s.getName() != null)
			{
				insertPlaceholders.append(s.getName());
				insertPlaceholders.append("\n");
			}
		}
		/* ------------------------------------------------------- */
		// Initiating the controller for the text processing software
		/* ------------------------------------------------------- */
		Thread t = new Thread() {
			
			public void run() {
				/* ================================================== */
				DocumentController controller = LetterTemplateModule.getController();
				if (controller == null) {
				    logger.info("ControllerConfig.getController() returns NULL....stopping here");
				    MainFrame.getInstance().setWaitCursor(false);
				    return;
				}
				try {
					/* ------------------------------------------------------- */
					// Create a new document on the client-side
					/* ------------------------------------------------------- */
					MainFrame.getInstance().setWaitCursor(true);

					if (!ControllerConfig.getLocalTemplatePath()
									.equalsIgnoreCase(LetterTemplateSettings.DEFAULT)) {
						/* ------------------------------------------------------- */
						// import the selected template
						// or create an empty one if null
						/* ------------------------------------------------------- */
						if (importFile != null && importFile.exists()) {
							/* ------------------------------------------------------- */
							controller.setDocument(FileUtils.readFile(importFile),
												   ControllerConfig.getLocalLetterPath());
							/* ------------------------------------------------------- */
						}
						else {
							/* ------------------------------------------------------- */
							// create the empty document
							/* ------------------------------------------------------- */
							controller.createNewDocument(ControllerConfig.getLocalTemplatePath());
							/* ------------------------------------------------------- */
						}
						/* ------------------------------------------------------- */
					} else {
						/* ------------------------------------------------------- */
						if (importFile != null && importFile.exists()) {
							controller.setDocument(FileUtils.readFile(importFile));
						}
						else {
							controller.createNewDocument();
						}
						/* ------------------------------------------------------- */
					}
					/* ------------------------------------------------------- */
					// open the word processing software
					/* ------------------------------------------------------- */
					
					controller.open(DocumentController.TYPE_NEW_TEMPLATE);
					/* ------------------------------------------------------- */
					// insert the placeholders
					/* ------------------------------------------------------- */
					
					if (insertPlaceholders != null)
					{
						controller.append(insertPlaceholders.toString());
					}
					/* ------------------------------------------------------- */
					// lock set the waitcursor
					/* ------------------------------------------------------- */
					MainFrame.getInstance().setWaitCursor(false);
					/* ------------------------------------------------------- */
					controller.waitForUserInput();
					/* ------------------------------------------------------- */
					lu.tudor.santec.gecamed.core.gui.controller.data.State state = controller
							.getState();
					if (state.isSaved()) {
						/* ------------------------------------------------------- */
						// When saved getting the session bean to store the
						// file
						// on the server
						/* ------------------------------------------------------- */
						// Getting the filename of the local document
						/* ------------------------------------------------------- */
						File document = controller.getDocumentbyFile();
						/* ------------------------------------------------------- */
						// Saving the document on the server
						/* ------------------------------------------------------- */
						LetterTemplateInterface manager = (LetterTemplateInterface) ManagerFactory
															.getRemote(LetterTemplateBean.class);
						
						String filename = manager.setTemplateBinary(
														document.getName(), 
														controller.getDocument());

						if (ControllerConfig.deleteDocuments()) {
							/* ------------------------------------------------------- */
							// Delete the local document
							controller.deleteDocument();
							/* ------------------------------------------------------- */
						}
						/* ------------------------------------------------------- */
						// Saving the filename when no name was provided by the user
						/* ------------------------------------------------------- */
						String tpl_name;
						if (templatename == null || "".equals(templatename.trim())) {
							tpl_name = document.getName();
						} else {
							tpl_name = templatename;
						}
						/* ------------------------------------------------------- */
						// Creating the template and storing in the database
						/* ------------------------------------------------------- */
						LetterTemplate template = new LetterTemplate();
						template.setCreatedOn(new Date());
						template.setCreatedBy(GECAMedModule
								.getCurrentPhysician().getId());
						/* ------------------------------------------------------- */
						template.setModifiedOn(new Date());
						template.setModifiedBy(GECAMedModule
								.getCurrentPhysician().getId());
						template.setName(tpl_name);
						
						template.setType(templateType);
						template.setAddressType(addressType);
						
						template.setGeneratedFileName(filename);
						template.setPhysicianId(GECAMedModule.getCurrentPhysician().getId());
						/* ------------------------------------------------------- */
						// set the mimetype
						/* ------------------------------------------------------- */
						if (controller instanceof WordController) {
							/* ------------------------------------------------------- */
							template.setMimetype(ControllerConfig.MIME_WORD);
							/* ------------------------------------------------------- */
						} else if (controller instanceof WriterController) {
							/* ------------------------------------------------------- */
							template.setMimetype(ControllerConfig.MIME_WRITER);
							/* ------------------------------------------------------- */
						} else {
							/* ------------------------------------------------------- */
							template.setMimetype(ControllerConfig.MIME_LETTER);
							/* ------------------------------------------------------- */
						}
						/* ------------------------------------------------------- */
						// save if the templates requires a contact
						/* ------------------------------------------------------- */
//						if (insertPlaceholders.toString().toUpperCase().contains("CONTACT"))
//							template.setRequiresContact(true);
						template.setRequiresContact(controller.containsContactInfo());
						/* ------------------------------------------------------- */
						// save
						/* ------------------------------------------------------- */
						manager.addTemplate(template);
						/* ------------------------------------------------------- */
						// Update the list of all templates in the
						// LetterTemplateModule
						/* ------------------------------------------------------- */
//						LetterTemplateModule.getInstance().updateList(0);
//						
//						LetterTemplateModule
//								.getInstance()
//								.getCbModel()
//								.addElement(templateType);
//						
//						LetterTemplateModule
//								.getInstance()
//								.getDetails()
//								.getCbModel()
//								.addElement(templateType);
						
						LetterTemplateModule.getInstance().refreshTemplateTypes();
						LetterTemplateModule.getInstance().refresh();
						/* ------------------------------------------------------- */
					} else {
						/* ------------------------------------------------------- */
						// if not saved
					    	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");
						}
						/* ------------------------------------------------------- */
					}
				} catch (Throwable e) {
					/* ------------------------------------------------------- */
       				    logger.log(Level.WARN, "Error creating template: ", e);
					MainFrame.getInstance().setWaitCursor(false);
					JOptionPane
							.showMessageDialog(
									parentPanel,
									Translatrix
											.getTranslationString("LetterTemplateModule.dialog.error.templatecreating"),
									Translatrix
											.getTranslationString("LetterTemplateModule.dialog.error.title"),
									JOptionPane.ERROR_MESSAGE);
					System.out.println(e.getLocalizedMessage());
					/* ------------------------------------------------------- */
				}
				try {
					LetterTemplateModule.getInstance().refresh();			
				} catch (Exception e) {}
			}
		};
		t.start();
//		} else {
//			JOptionPane
//					.showMessageDialog(
//							parentPane,
//							Translatrix
//									.getTranslationString("LetterTemplateModule.dialog.error.type"),
//							Translatrix
//									.getTranslationString("LetterTemplateModule.dialog.error.title"),
//							JOptionPane.ERROR_MESSAGE);
//		}
	}
	

}
