/*******************************************************************************
 * 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.event.ActionEvent;
import java.io.File;
import java.util.Date;

import javax.swing.ImageIcon;
import javax.swing.JList;
import javax.swing.JOptionPane;

import lu.tudor.santec.gecamed.core.gui.GECAMedAction;
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.letter.ejb.entity.beans.LetterTemplate;
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;

/*
 * OpenTemplateAction opens a template in the text processing software.
 */

public class OpenTemplateAction extends GECAMedAction {

    	/**
	 * static logger for this class
	 */
	private static Logger logger = Logger
		.getLogger(OpenTemplateAction.class.getName());
    
	private static final long serialVersionUID = 1L;

	public OpenTemplateAction(GECAMedModule p_Parent, String p_Name,
			ImageIcon p_Icon, Integer p_Shortcut, boolean p_IsMenuAction,
			boolean p_IsTopBarAction, boolean p_IsBottomBarAction) {

		super(p_Parent, p_Name, p_Icon, p_Shortcut, p_IsMenuAction,
				p_IsTopBarAction, p_IsBottomBarAction);

	}

	public void actionPerformed(ActionEvent p_Event) 
	{
		openTemplate(false);
	}
	
	
	public void openTemplate (final boolean update)
	{
		// Get the list with the templates

		final JList list = LetterTemplateModule.getInstance().getList();

		new Thread() {
			public void run() {
				// Get the index of the selected template in the list

				int index = list.getSelectedIndex();

				if (index > -1) {
					MainFrame.getInstance().setWaitCursor(true);

					// Get the controller for the configured text processing
					// software
					DocumentController controller = LetterTemplateModule.getController();
					
					if (controller == null) {
					    logger.info("ControllerConfig.getController() returns NULL....stopping here");
					    MainFrame.getInstance().setWaitCursor(false);
					    return;
					}
					
					try {
						// Get the template itself
						LetterTemplate letterTemplate = (LetterTemplate) list
								.getSelectedValue();

						byte[] filebytes = null;

						try {
							// Get the bytes of the template
							filebytes = LetterTemplateModule.getInstance()
									.getManager().getTemplateBinary(
											letterTemplate);
						} catch (Exception e) {
						    logger.log(Level.WARN, "Error loading template File " + letterTemplate.getGeneratedFileName() 
						    		+ ".\n" + e.getMessage());
						    
							JOptionPane.showMessageDialog(
											LetterTemplateModule.getInstance().getContentPane(),
											Translatrix.getTranslationString("LetterTemplateModule.dialog.error.outofsync") + "\n" +
											LetterTemplateModule.getInstance().getManager().getServerTemplateDir() + File.separator + 
											letterTemplate.getGeneratedFileName(),
											Translatrix.getTranslationString("LetterTemplateModule.dialog.error.title"),
											JOptionPane.ERROR_MESSAGE);
							MainFrame.getInstance().setWaitCursor(false);
							return;
						}
						// Set the local file to its configured path
						if (!ControllerConfig.getLocalTemplatePath()
								.equalsIgnoreCase(
										LetterTemplateSettings.DEFAULT))
							controller.setDocument(filebytes, ControllerConfig
									.getLocalTemplatePath());
						else
							controller.setDocument(filebytes);

						// Open the document
						controller.setPlaceholderVersion(letterTemplate.getPlaceholderVersion());
						controller.open(DocumentController.TYPE_OPEN_TEMPLATE);

						MainFrame.getInstance().setWaitCursor(false);
						
						if (update)
						{
							controller.updatePlaceholders();
						}

						// Waiting that user quits the application
						controller.waitForUserInput();

						// Get the state in order to know if the docuemnt was
						// saved or not
						lu.tudor.santec.gecamed.core.gui.controller.data.State state = controller
								.getState();

						if (state.isSaved()) {
							// If it was saved get the local document
							File document = controller.getDocumentbyFile();

							// Save the file physically on the server an get the
							// path of the lcoation
							String filename = LetterTemplateModule
									.getInstance().getManager()
									.setTemplateBinary(document.getName(),
											controller.getDocument());

							if (ControllerConfig.deleteDocuments()) {
								// Delete the local document
								controller.deleteDocument();
							}

							// recheck, whether there are contact information
							letterTemplate.setRequiresContact(controller.containsContactInfo());
							
							// Save the path of the file into the database
							letterTemplate.setGeneratedFileName(filename);							
							letterTemplate.setPlaceholderVersion(controller.getPlaceholderVersion());
							letterTemplate.setModifiedBy(GECAMedModule
									.getCurrentPhysician().getId());
							letterTemplate.setModifiedOn(new Date());

							// Store the template back into the database
							// (Override)
							LetterTemplateModule.getInstance().getManager()
									.addTemplate(letterTemplate);
							LetterTemplateModule.getInstance().updateList(
									LetterTemplateModule.getInstance()
											.getList().getSelectedIndex());

						} else {
							if (ControllerConfig.deleteDocuments()) {
								// Delete the local document
								controller.deleteDocument();
							}
						}
					} catch (Throwable e) {
					    logger.log(Level.WARN, "Error opening template: ", e);
						MainFrame.getInstance().setWaitCursor(false);
						JOptionPane.showMessageDialog(
										LetterTemplateModule.getInstance().getContentPane(),
										Translatrix.getTranslationString("LetterTemplateModule.dialog.error.open"),
										Translatrix.getTranslationString("LetterTemplateModule.dialog.error.title"),
										JOptionPane.ERROR_MESSAGE);

					}
				}
			}

		}.start();
	}
}
