package lu.tudor.santec.gecamed.formeditor.gui.view.dialog;

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.ButtonModel;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.filechooser.FileFilter;

import lu.tudor.santec.gecamed.core.ejb.entity.beans.Template;
import lu.tudor.santec.gecamed.core.ejb.entity.beans.XSLTemplate;
import lu.tudor.santec.gecamed.core.ejb.session.beans.TemplateManagerBean;
import lu.tudor.santec.gecamed.core.ejb.session.interfaces.TemplateManagerInterface;
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.xslfo.TransFOmer;
import lu.tudor.santec.gecamed.core.gui.widgets.GECAMedBaseDialogImpl;
import lu.tudor.santec.gecamed.core.utils.AutoEncodingFileReader;
import lu.tudor.santec.gecamed.core.utils.FileUtils;
import lu.tudor.santec.gecamed.core.utils.ManagerFactory;
import lu.tudor.santec.gecamed.formeditor.ejb.entity.beans.FormTemplate;
import lu.tudor.santec.gecamed.formeditor.gui.FormEditorModule;
import lu.tudor.santec.gecamed.formeditor.gui.controller.AbstractListener;
import lu.tudor.santec.gecamed.formeditor.gui.view.XMLEditDialog;
import lu.tudor.santec.i18n.Translatrix;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.xml.JRXmlLoader;

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

import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.forms.layout.RowSpec;
import com.jgoodies.forms.layout.Sizes;


public class PrintTemplateDialog extends GECAMedBaseDialogImpl
{
	/* ======================================== */
	// 		CONSTANTS
	/* ======================================== */
	
	private static final long serialVersionUID = 1L;
	
	private static final RowSpec EMPTY_ROW 		= new RowSpec(Sizes.pixel(5));
	private static final RowSpec DEFAULT_ROW 	= new RowSpec(RowSpec.FILL, Sizes.pixel(25), 0.0);
	
	private static final String DOT = ".";
	
	private static final String SUFFIXE_JRXML 	= ".jrxml";
	private static final String SUFFIXE_XSL 	= ".xsl";
	
	
	
	/* ======================================== */
	// 		MEMBERS
	/* ======================================== */
	
	/** the logger Object for this class */
	private static Logger logger = Logger.getLogger(PrintTemplateDialog.class.getName());
	
	private static String[] defaultFileExtensions 		= new String[TransFOmer.SUPPORTED_OUTPUT_TYPES_FOR_TEXT.length];
	
//	private static Document forcedHtmlExtensionDocument = new JTextField("html").getDocument();
	
	private static TemplateManagerInterface templateManager;
	
	private static JFileChooser fileChooser;
	private static FileFilter	iReportFilter; 
	private static FileFilter	xslFilter;
	
	
	private FormTemplate 	template;
	private Template 		reportTemplate;
	
	private JTextField 		reportNameField;
	private JButton 		reportUnloadButton;
	private JButton 		reportExportButton;
	
	private List<XslRow> 	xslList;
	private JPanel 			xslListPanel;
	private FormLayout 		xslListLayout;
	private ButtonGroup 	historyGroup;

	private JLabel 			xslNameLabel;
	private JLabel 			xslExtensionLabel;
	private JLabel 			xslHistoryLabel;
	private JLabel 			xslEditorLabel;
	private JLabel 			xslPrintLabel;
	
	private List<XSLTemplate> loadedTemplates;
	
	private XMLEditDialog	editor;
	
	
	
	/* ======================================== */
	// 		CONSTRUCTORS
	/* ======================================== */
	
	static 
	{
		for (int index = 0; index < defaultFileExtensions.length; index++)
			defaultFileExtensions[index] = TransFOmer.SUPPORTED_OUTPUT_TYPES_FOR_TEXT[index].getExtension();
	}
	
	
	public PrintTemplateDialog ()
	{
		super(MainFrame.getInstance(), 
				Translatrix.getTranslationString("formeditor.printTemplateDialog.title"),
				OK_CANCEL_APPLY_BUTTON_MODE);
		
		this.setMinimumSize(new Dimension(440, 0));

		CellConstraints cc = new CellConstraints();
		JScrollPane 	scrollPane;
		JPanel 	panel;
		JLabel 	label;
		JButton button;
		int 	row = 0;

		// FILE CHOOSER
		fileChooser 	= new JFileChooser();
		iReportFilter 	= new FileFilter()
		{
			@Override
			public String getDescription() 
			{
				return SUFFIXE_JRXML;
			}
			
			@Override
			public boolean accept(File f) 
			{
				return f.getName().endsWith(SUFFIXE_JRXML) || f.isDirectory();
			}
		};
		xslFilter 		= new FileFilter() 
		{
			@Override
			public String getDescription() 
			{
				return SUFFIXE_XSL;
			}
			@Override
			public boolean accept(File f) 
			{
				return f.getName().endsWith(SUFFIXE_XSL) || f.isDirectory();
			}
		};
		
		editor = new XMLEditDialog(this, true);
		
		mainPanel.setLayout(new FormLayout("5px, f:385:g, 5px", 
				"5px,f:p," + 	// iReport headline
				"5px,f:p," + 	// iReport management
				"5px,f:p," + 	// XSL headline
				"5px,f:min(300px;d):g," + // XSL management
				"5px,f:p," + 	// add XSL button & XSL example
//				"5px,f:p"  + 	// XSL example
				""));
		
		// headline iReport
		label = new JLabel(Translatrix.getTranslationString("formeditor.printTemplateDialog.reportTemplate"));
		label.setOpaque(false);
		mainPanel.add(label, cc.xy(2, row+=2));
		
		// manage iReport
		panel = new JPanel(new FormLayout("f:max(200px;p), 5px, f:25px, 5px, f:25px, 5px, f:25px", "f:25px"));
		panel.setOpaque(false);
		mainPanel.add(panel, cc.xy(2, row+=2));
		
		reportNameField = new JTextField();
		reportNameField.setEditable(false);
		panel.add(reportNameField, cc.xy(1, 1));
		
		// define the browse button
		button = new JButton(GECAMedModule.getSmallIcon(GECAMedIconNames.OPEN));
		button.setToolTipText(
				Translatrix.getTranslationString("formeditor.browse"));
		button.addActionListener(new ActionListener() 
		{
			public void actionPerformed(ActionEvent e) 
			{
				chooseIReportTemplate();
			}
		});
		panel.add(button, cc.xy(3, 1));
		
		reportExportButton = new JButton(GECAMedModule.getSmallIcon(GECAMedIconNames.EXPORT));
		reportExportButton.setToolTipText(Translatrix.getTranslationString("formeditor.printTemplateDialog.reportExportButton"));
		reportExportButton.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent e)
			{
				exportIReportTemplate();
			}
		});
		panel.add(reportExportButton, cc.xy(5, 1));
		
		// define the unload button
		reportUnloadButton = new JButton(GECAMedModule.getSmallIcon(GECAMedIconNames.MESSAGE_DELETE));
		reportUnloadButton.setToolTipText(
				Translatrix.getTranslationString("formeditor.ireporttemplate_unload_tooltip"));
		reportUnloadButton.addActionListener(new AbstractListener() 
		{
			public void actionPerformed(ActionEvent e) 
			{
				setReport(null);
			}
		});
		panel.add(reportUnloadButton, cc.xy(7, 1));
		
		// headline XSL templates
		label = new JLabel(Translatrix.getTranslationString("formeditor.printTemplateDialog.xslTemplates"));
		label.setOpaque(false);
		mainPanel.add(label, cc.xy(2, row+=2));
		
		// manage XSL templates
		xslListPanel 	= new JPanel();
		xslListPanel.setOpaque(false);
		
		scrollPane = new JScrollPane(xslListPanel);
		scrollPane.setOpaque(false);
		scrollPane.getViewport().setOpaque(false);
		scrollPane.setBorder(BorderFactory.createEmptyBorder());
		scrollPane.getVerticalScrollBar().setUnitIncrement(16);
		mainPanel.add(scrollPane, cc.xy(2, row+=2));
		
		
		// add the XSL management headline
		xslNameLabel 	= new JLabel(Translatrix.getTranslationString("formeditor.printTemplateDialog.xslTemplateName"));
		xslNameLabel.setOpaque(false);
		xslExtensionLabel = new JLabel(Translatrix.getTranslationString("formeditor.printTemplateDialog.xslTemplateFileExtension"));
		xslHistoryLabel = new JLabel(FormEditorModule.getSmallIcon("history.png"));
		xslHistoryLabel.setToolTipText(Translatrix.getTranslationString("formeditor.printTemplateDialog.xslTemplateHistoryToolTip"));
		xslHistoryLabel.setOpaque(false);
		xslEditorLabel 	= new JLabel(FormEditorModule.getSmallIcon("text_editor.png"));
		xslEditorLabel.setToolTipText(Translatrix.getTranslationString("formeditor.printTemplateDialog.xslTemplateEditableToolTip"));
		xslEditorLabel.setOpaque(false);
		xslPrintLabel 	= new JLabel(GECAMedModule.getSmallIcon(GECAMedIconNames.PRINT));
		xslPrintLabel.setToolTipText(Translatrix.getTranslationString("formeditor.printTemplateDialog.xslTemplatePrintableToolTip"));
		xslPrintLabel.setOpaque(false);
		
		panel = new JPanel(new FormLayout("p, 0px:g, p", "f:p"));
		panel.setOpaque(false);
		mainPanel.add(panel, cc.xy(2, row+=2));
		// add XSL button
		button = new JButton(
				Translatrix.getTranslationString("formeditor.printTemplateDialog.xslTemplateAddButton"),
				GECAMedModule.getSmallIcon(GECAMedIconNames.ADD_LINE));
//		mainPanel.add(button, cc.xy(2, row+=2, CellConstraints.LEFT, CellConstraints.FILL));
		panel.add(button, cc.xy(1, 1, CellConstraints.LEFT, CellConstraints.FILL));
		button.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent e)
			{
				addXsl(null);
			}
		});
		

		// THE DATA-XML EXAMPLE
		button = new JButton(
				Translatrix.getTranslationString("formeditor.templatesettings.showDataXmlExample"));
		button.setToolTipText(
				Translatrix.getTranslationString("formeditor.templatesettings.showDataXmlExampleToolTip"));
		button.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent e)
			{
				editor.showXmlDataExample(template, null);
			}
		});
//		mainPanel.add(button, cc.xy(2, row+=2, CellConstraints.RIGHT, CellConstraints.FILL));
		panel.add(button, cc.xy(3, 1, CellConstraints.LEFT, CellConstraints.FILL));
	}
	
	
	
	/* ======================================== */
	// 		CLASS BODY
	/* ======================================== */
	
	public FormTemplate show (FormTemplate template)
	{
		this.template = template;
		initFormTemplate();
		setVisible(true);
		
		return this.template;
	}
	
	
	
	/* ======================================== */
	// 		OVERRIDDEN METHODS
	/* ======================================== */
	
	@Override
	public void okActionCalled()
	{
		save();
		super.okActionCalled();
	}
	
	
	@Override
	public void applyActionCalled()
	{
		save();
		super.applyActionCalled();
	}
	
	
//	@Override
//	public void cancelActionCalled()
//	{
//		super.cancelActionCalled();
//	}
	
	
	
	/* ======================================== */
	// 		HELP METHODS
	/* ======================================== */
	
	private void initFormTemplate ()
	{
		// prepare the dialog for a new form template
		CellConstraints cc = new CellConstraints();
		
		// rebuild
		setReport(template.getJasperTemplate());
		
		// reset XSL management list
		xslListPanel.removeAll();
		xslListLayout 	= new FormLayout(
				"f:max(200px;p)," + // name field
				"f:p," + 			// dot label
				"f:50px," + 		// ending field
				"5px,f:25px," + 	// edit button
				"5px,f:25px," + 	// load button
				"5px,f:25px," + 	// remove button
				"5px,c:p," + 		// history box
				"5px,c:p," + 		// edit box
				"5px,c:p" + 		// print box
				""); 
		xslListPanel.setLayout(xslListLayout);
		xslListLayout.appendRow(DEFAULT_ROW);
		xslListPanel.add(xslNameLabel, 		cc.xy(1, 1));
		xslListPanel.add(xslExtensionLabel, cc.xy(3, 1));
		xslListPanel.add(xslHistoryLabel, 	cc.xy(11,1));
		xslListPanel.add(xslEditorLabel, 	cc.xy(13,1));
		xslListPanel.add(xslPrintLabel, 	cc.xy(15,1));
		
		historyGroup = new ButtonGroup()
		{
			private static final long serialVersionUID = 1L;
			
			@Override
			public void setSelected(ButtonModel m, boolean b)
			{
				if (!b && m != null && m.isSelected()) 
					 clearSelection();
				else super.setSelected(m, b);
			}
		};
		
		try
		{
			TemplateManagerInterface manager = getTemplateManager();
			loadedTemplates = manager.getXSLTemplates(XSLTemplate.TYPE_FORM_EDITOR, template.getId(), null);
			xslList = new ArrayList<PrintTemplateDialog.XslRow>(loadedTemplates.size());
			for (XSLTemplate t : loadedTemplates)
			{
				addXsl(t);
			}
		} 
		catch (Exception e)
		{
			logger.log(Level.ERROR, e.getMessage(), e);
		}
		
		adjust();
	}
	
	
	private void addXsl (final XSLTemplate xsl)
	{
		CellConstraints cc = new CellConstraints();
		int row;
		
		xslListLayout.appendRow(EMPTY_ROW);
		xslListLayout.appendRow(DEFAULT_ROW);
		row = xslListLayout.getRowCount();
		
		XslRow rowData = new XslRow(xsl);
		xslList.add(rowData);
		
		xslListPanel.add(rowData.nameField, 	cc.xy(1, row));
		xslListPanel.add(rowData.dotLabel, 		cc.xy(2, row));
		xslListPanel.add(rowData.extensionBox, 	cc.xy(3, row));
		xslListPanel.add(rowData.editButton, 	cc.xy(5, row));
		xslListPanel.add(rowData.loadButton, 	cc.xy(7, row));
		xslListPanel.add(rowData.removeButton, 	cc.xy(9, row));
		xslListPanel.add(rowData.useForHistory, cc.xy(11,row));
		xslListPanel.add(rowData.useToEdit, 	cc.xy(13,row));
		xslListPanel.add(rowData.useToPrint, 	cc.xy(15,row));
		
		adjust();
	}
	
	
	private void setReport (Template template)
	{
		reportTemplate = template;
		if (reportTemplate == null)
		{
			reportUnloadButton.setEnabled(false);
			reportExportButton.setEnabled(false);
			reportNameField.setText("");
		}
		else
		{
			reportUnloadButton.setEnabled(true);
			reportExportButton.setEnabled(true);
			reportNameField.setText(reportTemplate.getName());
		}
	}

	
	private void chooseIReportTemplate()
	{
		fileChooser.setFileFilter(iReportFilter);
		int buttonOption = fileChooser.showOpenDialog(this);
		
		if (buttonOption == JFileChooser.APPROVE_OPTION) 
		{
			File jrxmlFile = fileChooser.getSelectedFile();

			if (jrxmlFile == null) 
				return;
			
			try 
			{
				String jrxml = loadFileAsString(jrxmlFile);
				
				JasperDesign jasperDesign;
				JasperReport jasperReport;
				try 
				{
					// try to parse the XML-file 
					jasperDesign = JRXmlLoader.load(jrxmlFile);
					
//					TemplateManagerInterface templateManager = getTemplateManager();
//					
//					// try to compile the design
//					jasperReport = templateManager.compileReport(jasperDesign);
					jasperReport = JasperCompileManager.compileReport(jasperDesign);
				} 
				catch (Exception e) 
				{
					GECAMedBaseDialogImpl.showMessageDialog(this, 
							Translatrix.getTranslationString("formeditor.ireporttemplate_parsing_error_title"), 
							Translatrix.getTranslationString("formeditor.ireporttemplate_parsing_error") +
							e.getMessage(), 
							GECAMedBaseDialogImpl.OK_BUTTON_MODE);
					
					return;
				}
				
				ByteArrayOutputStream jasperReportBytes = new ByteArrayOutputStream();
				ObjectOutputStream oos = new ObjectOutputStream(jasperReportBytes);
				oos.writeObject(jasperReport);
				oos.flush();
				oos.close();
				jasperReportBytes.close();
				
				/* **********  define the new template  ********** */
				Template template = new Template();
				template.setType(FormTemplate.REPORT_TEMPLATE_TYPE);
				template.setPhysicianID(MainFrame.getCurrentPhysician().getId());
				template.setName(jasperDesign.getName());
				template.setJrxml(jrxml.getBytes());
				template.setJasper(jasperReportBytes.toByteArray());
				setReport(template);
				/* **************************************** */
			} 
			catch (IOException e) 
			{
				logger.log(Level.ERROR, e.getMessage(), e);
			}
		}
	}
	
	
	private void exportIReportTemplate ()
	{
		Template 	report 			= template.getJasperTemplate();
    	String 		templateName 	= report.getName();
	    byte[] 		templateData 	= report.getJrxml();
	    
		fileChooser.setFileFilter(iReportFilter);
		fileChooser.setSelectedFile(new File(templateName + ".jrxml"));
		
		if (fileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) 
		{
			File jrxmlFile = fileChooser.getSelectedFile();
			if (jrxmlFile == null) 
				return;
			
			try 
			{
				FileUtils.writeFile(templateData, jrxmlFile);
			} 
			catch (IOException e) 
			{
				logger.log(Level.ERROR, e.getMessage(), e);
			}
		}
	}
	
	
	private String loadFileAsString (File file)
	{
//		FileInputStream 		fis		= null;
//		InputStreamReader 		isr		= null;
		AutoEncodingFileReader	encoder	= null;
		InputStreamReader		isr;
		BufferedReader 			reader;
		StringBuffer 			text;
		
		
		try
		{
//			fis 	= new FileInputStream(file);
//			isr 	= new InputStreamReader(fis);
			encoder = new AutoEncodingFileReader(file);
			isr		= encoder.read();
			reader 	= new BufferedReader(isr);
			text 	= new StringBuffer();
			
			String line;
			while ((line = reader.readLine()) != null)
				text.append(line).append("\n");
			
			reader.close();
			
			return text.toString();
		} 
		catch (Exception e)
		{
			logger.log(Level.ERROR, e.getMessage(), e);
		}
		finally
		{
//			if (isr != null)		isr.close();
//			if (fis != null)		fis.close();
			if (encoder != null)	encoder.closeStream();
		}
		
		return null;
	}
	
	
	private void save ()
	{
		TemplateManagerInterface	manager 			= getTemplateManager();
		List<XSLTemplate>			currentTemplates 	= new LinkedList<XSLTemplate>();
		
		
		if (reportTemplate != null || template.getJasperTemplate() != null)
		{
			// the iReport template was set, save it
			try
			{
				template		= manager.saveTemplate(reportTemplate, template.getId());
				reportTemplate	= template.getJasperTemplate();
			}
			catch (Exception e)
			{
				logger.log(Level.ERROR, "Error while trying to store iReport template for form template", e);
			}
		}
		
		// save all templates 
		for (XslRow row : xslList)
		{
			if (row == null || row.data == null)
				continue;
			
			// commit changes
			row.data.setName(row.getFullName());
			row.data.setUseForHistory(row.useForHistory.isSelected() ? Boolean.TRUE : Boolean.FALSE);
			row.data.setUseToEdit	 (row.useToEdit.isSelected()	 ? Boolean.TRUE : Boolean.FALSE);
			row.data.setUseToPrint	 (row.useToPrint.isSelected()	 ? Boolean.TRUE : Boolean.FALSE);
			
			try
			{
				row.data = manager.saveTemplate(row.data);
				currentTemplates.add(row.data);
				if (!loadedTemplates.contains(row.data))
					loadedTemplates.add(row.data);
			}
			catch (Exception e)
			{
				logger.log(Level.ERROR, e.getMessage(), e);
			}
		}
		
		// delete those templates that aren't in the list anymore
		for (XSLTemplate t : loadedTemplates)
		{
			if (t != null && 
					(	t.getId() == null 
					|| !currentTemplates.contains(t)))
			{
				try 
				{
					manager.deleteTemplate(t);
				}
				catch (Exception e)
				{
					logger.log(Level.ERROR, e.getMessage(), e);
				}
			}
		}
	}
	
	
	private TemplateManagerInterface getTemplateManager ()
	{
		// get the template manager
		if (templateManager == null)
			templateManager = (TemplateManagerInterface) ManagerFactory.getRemote(TemplateManagerBean.class);
		
		return templateManager;
	}
	
	
	private void adjust ()
	{
		validate();
		pack();
		setLocationRelativeTo(getOwner());
	}
	
	
	
	/* ======================================== */
	// 		CLASS: XslRow
	/* ======================================== */
	
	private class XslRow implements ActionListener //, ChangeListener
	{
		/* ======================================== */
		// 		MEMBERS
		/* ======================================== */
		
		private XSLTemplate 	data;
		
		private JTextField 		nameField;
		private JLabel 			dotLabel;
		private JComboBox 		extensionBox;
//		private Document 		extensionDoc;
		
		private JButton 		editButton;
		private JButton 		loadButton;
		private JButton 		removeButton;
		
		private JRadioButton 	useForHistory;
		private JCheckBox 		useToEdit;
		private JCheckBox 		useToPrint;
		
		
		
		/* ======================================== */
		// 		CONSTRUCTOR
		/* ======================================== */
		
		public XslRow (XSLTemplate xslTemplate)
		{
			nameField 		= new JTextField();
			dotLabel 		= new JLabel(DOT);
			dotLabel.setOpaque(false);
			extensionBox 	= new JComboBox(defaultFileExtensions);
//			extensionDoc 	= extensionField.getDocument();
			
			editButton 		= new JButton(FormEditorModule.getSmallIcon("text_editor.png"));
			editButton.setToolTipText(Translatrix.getTranslationString("formeditor.printTemplateDialog.xslEditButton"));
			editButton.addActionListener(this);
			
			loadButton 		= new JButton(GECAMedModule.getSmallIcon(GECAMedIconNames.OPEN));
			loadButton.setToolTipText(Translatrix.getTranslationString("formeditor.printTemplateDialog.xslLoadButton"));
			loadButton.addActionListener(this);
			
			removeButton	= new JButton(GECAMedModule.getSmallIcon(GECAMedIconNames.MESSAGE_DELETE));
			removeButton.setToolTipText(Translatrix.getTranslationString("formeditor.printTemplateDialog.xslRemoveButton"));
			removeButton.addActionListener(this);
			
			useForHistory 	= new JRadioButton();
			useForHistory.setOpaque(false);
			useForHistory.setToolTipText(Translatrix.getTranslationString("formeditor.printTemplateDialog.xslTemplateHistoryToolTip"));
//			useForHistory.addChangeListener(this);
			historyGroup.add(useForHistory);
			
			useToEdit 		= new JCheckBox();
			useToEdit.setOpaque(false);
			useToEdit.setToolTipText(Translatrix.getTranslationString("formeditor.printTemplateDialog.xslTemplateEditableToolTip"));

			useToPrint 		= new JCheckBox();
			useToPrint.setOpaque(false);
			useToPrint.setToolTipText(Translatrix.getTranslationString("formeditor.printTemplateDialog.xslTemplatePrintableToolTip"));
			
			if (xslTemplate == null)
			{
				data = new XSLTemplate();
//				data.setPhysicianId();
				data.setReferenceType(XSLTemplate.TYPE_FORM_EDITOR);
				data.setReferenceId(template.getId());
				data.setData(XMLEditDialog.getTemplate(data.getFileNameExtension()));
			}
			else data = xslTemplate;
			
			// split the filename into prefix and extension
			String 	extension 	= data.getFileNameExtension();
			String 	fileName 	= data.getFileNamePrefix();
			boolean history 	= data.getUseForHistory().booleanValue();
			
			nameField.setText(fileName);
			extensionBox.setSelectedItem(extension);
			extensionBox.setEditable(true);
			useForHistory.setSelected(history);
			useToEdit.setSelected(data.getUseToEdit().booleanValue());
			useToPrint.setSelected(data.getUseToPrint().booleanValue());
			
			if (!extensionBox.getSelectedItem().equals(extension))
				extensionBox.getEditor().setItem(extension);
		}
		
		
		public String getFullName ()
		{
			return new StringBuffer(nameField.getText())
					.append(DOT)
					.append(extensionBox.getSelectedItem())
					.toString();
		}
		
		
		public void actionPerformed(ActionEvent e)
		{
			Object source = e.getSource();
			
			if (source == editButton)
			{
				data.setName(nameField.getText() + DOT + extensionBox.getSelectedItem());
				// open the editor with the text of this 
				String xml = editor.editXml(data, template);
				data.setData(xml);
			}
			else if (source == loadButton)
			{
				// load an XML file as new template
				fileChooser.setFileFilter(xslFilter);
				int buttonOption = fileChooser.showOpenDialog(PrintTemplateDialog.this);
				
				if (buttonOption == JFileChooser.APPROVE_OPTION) 
				{
					File file = fileChooser.getSelectedFile();
					data.setData(loadFileAsString(file));
					
					if (nameField.getText() == null || nameField.getText().isEmpty())
						nameField.setText(file.getName().replaceAll("\\.[^\\.]+$", ""));
				}
			}
			else if (source == removeButton)
			{
				xslList.remove(removeMe());
				validate();
				adjust();
			}
		}


//		public void stateChanged(ChangeEvent e)
//		{
//			Object source = e.getSource();
//			
//			if (source == useForHistory)
//			{
//				boolean selected = useForHistory.isSelected();
//				if (selected && extensionField.getDocument() != forcedHtmlExtensionDocument)
//				{
//					extensionField.setDocument(forcedHtmlExtensionDocument);
//					extensionField.setEditable(false);
//				}
//				else if (!selected && extensionField.getDocument() == forcedHtmlExtensionDocument)
//				{
//					extensionField.setDocument(extensionDoc);
//					extensionField.setEditable(true);
//				}
//			}
//		}
		
		
		private int removeMe ()
		{
			int index;
			int row;
			
			// remove item from list and view
			synchronized (xslList)
			{
				index = xslList.indexOf(this);
//				for (index = 0; index < xslList.size(); index++)
//				{
//					if (xslList.get(index) == this)
//						break;
//				}
				
				historyGroup.remove(this.useForHistory);
				
				row = (index + 2) * 2 - 2;
				xslListPanel.remove(this.editButton);
				xslListPanel.remove(this.loadButton);
				xslListPanel.remove(this.nameField);
				xslListPanel.remove(this.dotLabel);
				xslListPanel.remove(this.extensionBox);
				xslListPanel.remove(this.removeButton);
				xslListPanel.remove(this.useForHistory);
				xslListPanel.remove(this.useToEdit);
				xslListPanel.remove(this.useToPrint);
				
				xslListLayout.removeRow(row);
				xslListLayout.removeRow(row);
			}
			return index;
		}
	}
}
