/*******************************************************************************
 * 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.core.gui.widgets.templates;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.io.InputStream;
import java.util.Date;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JPanel;
import javax.swing.JTextField;

import lu.tudor.santec.gecamed.core.ejb.entity.beans.Template;
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.utils.CustomFileFilter;
import lu.tudor.santec.gecamed.core.gui.utils.GECAMedGuiUtils;
import lu.tudor.santec.gecamed.core.gui.utils.WindowToolbox;
import lu.tudor.santec.gecamed.core.gui.widgets.ErrorDialog;
import lu.tudor.santec.gecamed.core.gui.widgets.GECAMedBaseDialogImpl;
import lu.tudor.santec.gecamed.core.gui.widgets.progress.ProgressEvent;
import lu.tudor.santec.gecamed.core.gui.widgets.progress.ProgressListener;
import lu.tudor.santec.gecamed.core.utils.FileUtils;
import lu.tudor.santec.gecamed.core.utils.JasperTemplateBean;
import lu.tudor.santec.i18n.Relocalizable;
import lu.tudor.santec.i18n.Translatrix;
import lu.tudor.santec.widgets.gui.ButtonFactory;

import org.apache.log4j.Logger;

import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;
import com.toedter.calendar.JDateChooser;

//***************************************************************************
//* Class Defintition                                                       *
//***************************************************************************

class TemplatePanel extends JPanel implements ActionListener,
											  PropertyChangeListener,
											  ProgressListener,
											  Relocalizable
	{
	private static final long serialVersionUID = 1L;
	
	/** the logger Object for this class */
	private static Logger logger = Logger.getLogger(TemplatePanel.class.getName());
		
	private TemplateGroupPanel	 m_Parent;
	private JTextField			 m_TemplateField;
	private JDateChooser		 m_TemplateExpiry;
	private JButton				 m_ChooseTemplateButton;
	private JButton				 m_DeleteTemplateButton;
	private Template			 m_Template;
	private TemplateWorker		 m_TemplateWorker;

	private JButton m_SaveTemplateButton;
		
	private static CustomFileFilter c_JRXMLFilter = new CustomFileFilter ("jrxml","JRXML Template Files"); 
		
//***************************************************************************
//* Class Constants                                                         *
//***************************************************************************

	private final static String c_Columns		= "3dlu,fill:max(75dlu;pref):grow," +
	  											  "3dlu,fill:max(75dlu;pref)," +
	  											  "3dlu,fill:max(3dlu;pref)," +
	  											  "3dlu,fill:max(3dlu;pref)," +
	  											  "3dlu,fill:max(3dlu;pref),3dlu";

	private final static String c_Rows			= "3dlu,fill:pref,3dlu";
	
//***************************************************************************
//* Constructor                                                             *
//***************************************************************************
	
public TemplatePanel (TemplateGroupPanel p_Parent, Template p_Template)	
	{
	FormLayout		l_Layout;
	CellConstraints	l_Constraints;
	
	m_Parent 	= p_Parent;
	m_Template 	= p_Template;
	
	l_Layout = new FormLayout (c_Columns,c_Rows);
	l_Constraints = new CellConstraints ();
	
	this.setLayout(l_Layout);
	
	m_TemplateField = new JTextField ();
	m_TemplateField.setToolTipText(Translatrix.getTranslationString("TemplatePanel.TemplateNameTip"));
	m_TemplateField.setEditable(false);
	
	m_TemplateExpiry = GECAMedGuiUtils.getDateChooser(false);
	m_TemplateExpiry.getCalendarButton().setToolTipText(Translatrix.getTranslationString("TemplatePanel.SetExpiryDateTip"));
	m_TemplateExpiry.addPropertyChangeListener(this);
	
	m_ChooseTemplateButton = ButtonFactory.createNarrowButton(GECAMedModule.getMiniIcon(GECAMedIconNames.TEMPLATE_OPEN));
	m_ChooseTemplateButton.setText ("");
	m_ChooseTemplateButton.setToolTipText(Translatrix.getTranslationString ("TemplatePanel.ChooseTemplateButtonTip"));
	m_ChooseTemplateButton.addActionListener(this);
	
	m_DeleteTemplateButton = ButtonFactory.createNarrowButton(GECAMedModule.getMiniIcon(GECAMedIconNames.TEMPLATE_DELETE));
	m_DeleteTemplateButton.setText ("");
	m_DeleteTemplateButton.setToolTipText(Translatrix.getTranslationString ("TemplatePanel.DeleteTemplateButtonTip"));
	m_DeleteTemplateButton.addActionListener(this);
	
	m_SaveTemplateButton = ButtonFactory.createNarrowButton(GECAMedModule.getMiniIcon(GECAMedIconNames.SAVE));
	m_SaveTemplateButton.setText ("");
	m_SaveTemplateButton.setToolTipText(Translatrix.getTranslationString ("TemplatePanel.SaveTemplateButtonTip"));
	m_SaveTemplateButton.addActionListener(this);
	
	this.relocalize();
	this.reflectTemplate (m_Template);
	
	this.add (m_TemplateField,    		l_Constraints.xy(2,2));
	this.add (m_TemplateExpiry, 		l_Constraints.xy(4,2));
	this.add (m_ChooseTemplateButton, 	l_Constraints.xy(6,2));
	this.add (m_SaveTemplateButton, 	l_Constraints.xy(8,2));
	this.add (m_DeleteTemplateButton, 	l_Constraints.xy(10,2));
	}	

//***************************************************************************
//* Class Primitives                                                        *
//***************************************************************************
//---------------------------------------------------------------------------

private File chooseTemplateFile ()
	{
	JFileChooser	l_FileChooser;
	File			l_ChosenFile = null;
	
	l_FileChooser = MainFrame.getFileChooser();
	l_FileChooser.setFileFilter (c_JRXMLFilter);
	
	if (l_FileChooser.showOpenDialog(WindowToolbox.getOwnerFrame(this)) == JFileChooser.APPROVE_OPTION)
		{
		l_ChosenFile = l_FileChooser.getSelectedFile();
		}
	
	return l_ChosenFile;
	}	

//---------------------------------------------------------------------------

private void setExpiryDate (Date p_Date)
	{
	m_TemplateExpiry.removePropertyChangeListener(this);
	m_TemplateExpiry.setDate(p_Date);
	m_TemplateExpiry.addPropertyChangeListener(this);
	}

//---------------------------------------------------------------------------

private void reset ()
	{
//	m_Template = null;
	m_TemplateField.setText ("");
	this.setExpiryDate(null);
	}

//---------------------------------------------------------------------------

private void reflectTemplate (Template p_Template)
	{
	if (p_Template != null)
		{
		m_TemplateField.setText (p_Template.getName());
		this.setExpiryDate (p_Template.getExpiry());
		}
	else this.reset ();
	}

//---------------------------------------------------------------------------
//***************************************************************************
//* Class Body                                                              *
//***************************************************************************
//---------------------------------------------------------------------------

public void setTemplate (Template p_Template)
	{
	m_Template = p_Template;
	this.reflectTemplate(m_Template);
	}

//---------------------------------------------------------------------------

public Template getTemplate ()
	{
	return m_Template;
	}

//---------------------------------------------------------------------------

public void enableDeleteButton (boolean p_EnableIt)
	{
	if (m_DeleteTemplateButton != null) 
		m_DeleteTemplateButton.setEnabled (p_EnableIt);
	}

//---------------------------------------------------------------------------

public void actionPerformed (ActionEvent p_Event)
	{
	File l_TemplateFile;
	
	if (p_Event.getSource().equals (m_ChooseTemplateButton))
		{
		l_TemplateFile = this.chooseTemplateFile();
		if (l_TemplateFile != null)
			{
			m_TemplateWorker = new TemplateWorker ();
			m_TemplateWorker.addProgressListener(this);

			m_TemplateWorker.setTemplate		(m_Template);
			m_TemplateWorker.setTemplateFile	(l_TemplateFile);
			m_TemplateWorker.setTemplateExpiry	(m_TemplateExpiry.getDate());
			
			if (m_Parent != null)
				{
				m_TemplateWorker.setTemplateType(m_Parent.getTemplateType());
				m_TemplateWorker.setPhysicianId (m_Parent.getPhysicianId());
				}
			m_TemplateWorker.importTemplate();
			}
		}
	else if (p_Event.getSource().equals (m_DeleteTemplateButton))
		{
		this.reset();
		if (m_Parent instanceof TemplateGroupPanel) m_Parent.removeTemplatePanel(this);
		}
	else if (p_Event.getSource().equals (m_SaveTemplateButton))
		{
	    		downloadTemplate();
		}
	} 
	

	private void downloadTemplate ()
	{
		try
		{
			String templateName;// = m_Parent.getTemplateType();
			byte[] templateData = null;
			InputStream templateStream = null;
			
			if (m_Template != null && !m_TemplateField.getText().equals(""))
			{
				// use custom template
				templateName = m_Template.getName();
				templateData = m_Template.getJrxml();
			}
			else
			{
				// use default template from resource path
//				templateName = m_Parent.getTemplateType();
				JasperTemplateBean template = JasperTemplateBean.getTemplateBean(m_Parent.getTemplateType(), false);
				templateName = template.getName();
//				String filePath = m_Parent.m_TemplateInterface.getDefaultTemplatePath(templateName);
//				filePath = filePath.replaceAll("\\.jasper", ".jrxml");
				templateStream = TemplatePanel.class.getResourceAsStream(template.getResourcePath());
			}
			
			JFileChooser l_FileChooser = MainFrame.getFileChooser();
			File l_ChosenFile = null;
			l_FileChooser.setFileFilter(c_JRXMLFilter);
			l_FileChooser.setSelectedFile(new File(templateName + ".jrxml"));
			
			if (l_FileChooser.showSaveDialog(WindowToolbox.getOwnerFrame(this)) == JFileChooser.APPROVE_OPTION)
			{
				l_ChosenFile = l_FileChooser.getSelectedFile();
				if (!l_ChosenFile.exists() || GECAMedBaseDialogImpl.showMessageDialog(
							MainFrame.getInstance(), 
							Translatrix.getTranslationString("TemplatePanel.fileExistsTitle"), 
							Translatrix.getTranslationString("TemplatePanel.fileExistsMessage"), 
							GECAMedBaseDialogImpl.YES_NO_BUTTON_MODE, 
							GECAMedModule.getBigIcon(GECAMedIconNames.INFO)) == GECAMedBaseDialogImpl.YES_OPTION)
				{
					if (templateData != null)
						FileUtils.writeFile(templateData, l_ChosenFile);
					else
						FileUtils.writeStreamToFile(templateStream, l_ChosenFile);
				}
			}
		}
		catch (Exception e)
		{
			ErrorDialog.showErrorDialog(MainFrame.getInstance(), e);
			logger.error("Error while trying to save a print template", e);
		}
	}

//---------------------------------------------------------------------------

public void propertyChange(PropertyChangeEvent p_Event) 
	{
	if (   (p_Event.getSource().equals(m_TemplateExpiry))
		&& ("date".equals(p_Event.getPropertyName()))) 
		{
		m_TemplateWorker = new TemplateWorker ();

		m_TemplateWorker.setTemplate		(m_Template);
		m_TemplateWorker.setTemplateExpiry	(m_TemplateExpiry.getDate());
		m_TemplateWorker.updateTemplate();
		}
	}

//---------------------------------------------------------------------------

public void relocalize() 
	{
	if (m_TemplateExpiry != null) 
		{
		m_TemplateExpiry.setLocale (Translatrix.getLocale());
		m_TemplateExpiry.setDateFormatString("d MMMM yyyy");   
		m_TemplateExpiry.getDateEditor().setLocale (Translatrix.getLocale());
		}

	if (m_ChooseTemplateButton != null)
		{
		m_ChooseTemplateButton.setText ("");
		m_ChooseTemplateButton.setToolTipText(Translatrix.getTranslationString ("TemplatePanel.ChooseTemplateButtonTip"));
		}
	
	c_JRXMLFilter.setDescription (Translatrix.getTranslationString ("TemplatePanel.JRXMLFiles"));
	}

//---------------------------------------------------------------------------

public void progressChanged (ProgressEvent p_Event) 
	{
	if (p_Event.getType() == ProgressEvent.c_Completed)
		{
		if (m_TemplateWorker instanceof TemplateWorker)
			{
			m_Template = m_TemplateWorker.getTemplate();
			this.reflectTemplate (m_Template);
			m_TemplateExpiry.removePropertyChangeListener(this);
			}
		}
	}


//---------------------------------------------------------------------------
//***************************************************************************
//* End of Class															*
//***************************************************************************


}

