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

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;

import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

import lu.tudor.santec.gecamed.core.gui.GECAMedIconNames;
import lu.tudor.santec.gecamed.core.gui.GECAMedModule;
import lu.tudor.santec.gecamed.core.gui.widgets.LimitTextField;
import lu.tudor.santec.gecamed.core.gui.widgets.ModuleHeader;
import lu.tudor.santec.gecamed.core.gui.widgets.NamedComponent;
import lu.tudor.santec.gecamed.core.utils.ManagerFactory;
import lu.tudor.santec.gecamed.formeditor.ejb.entity.beans.FormTemplate;
import lu.tudor.santec.gecamed.formeditor.ejb.session.beans.FormManagerImpl;
import lu.tudor.santec.gecamed.formeditor.ejb.session.interfaces.FormManager;
import lu.tudor.santec.gecamed.formeditor.gui.FormEditorModule;
import lu.tudor.santec.gecamed.formeditor.gui.controller.AbstractListener;
import lu.tudor.santec.gecamed.formeditor.gui.model.FormEditorModel;
import lu.tudor.santec.gecamed.formeditor.gui.model.FormModel;
import lu.tudor.santec.gecamed.formeditor.gui.view.dialog.PrintTemplateDialog;
import lu.tudor.santec.gecamed.patient.gui.PatientButtonPanel;
import lu.tudor.santec.i18n.Translatrix;

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

public class TemplateSettingsPanel extends PatientButtonPanel 
{
	private static final long serialVersionUID = 1L;
	
	private FormEditorModel model;
	private JTabbedPane 	tabbedPane;
	private JList 			templateList;
	
	private FormTemplate 	currentTemplate;
	
	private JButton 		saveButton;
	private JButton 		reloadButton;
	
	private JTextField 		nameField;
	private JTextField 		versionField;
	private JCheckBox 		subformOnlyBox;
	private JTextArea 		descriptionArea;
	
	private PrintTemplateDialog printTemplateDialog;
	
	
	
	public TemplateSettingsPanel (FormEditorModel model, String title, Color color) 
	{
		super(title, color, new JPanel());
		this.model = model;
		
		content.setLayout(new FormLayout("5px, f:150px, 5px", 
				"5px,f:p," + // save and reset button
				"5px,f:p," + // name
				"5px,f:p," + // version
				"5px,f:p," + // sub form only
				"5px,f:150px," + // description
				"5px,f:p," + // manage templates button
				"5px,0px:g"));
		CellConstraints cc = new CellConstraints();
		
		
		/* **********  save & reset buttons:  ********** */
		// SAVE BUTTON:
		JPanel saveResetPanel = new JPanel(new FormLayout(
				"p:g, f:32px, 5px, f:32px", "f:32px"));
		saveResetPanel.setOpaque(false);
		
		saveButton = new JButton("",
				GECAMedModule.getScaledIcon(GECAMedIconNames.SAVE, 32));
		saveButton.setToolTipText(Translatrix.getTranslationString("core.save"));
		ModuleHeader.addEffect(saveButton);
		saveButton.setEnabled(false);
		
		saveButton.addActionListener(new ActionListener() 
		{
			public void actionPerformed(ActionEvent e) 
			{
				saveTemplateSettings(e);
			}
		});
		
		// RELOAD BUTTON:
		reloadButton = new JButton("",
				GECAMedModule.getScaledIcon(GECAMedIconNames.RELOAD, 32));
		reloadButton.setToolTipText(Translatrix.getTranslationString("formeditor.reload"));
		ModuleHeader.addEffect(reloadButton);
		reloadButton.setEnabled(false);
		
		reloadButton.addActionListener(new ActionListener() 
		{
			public void actionPerformed(ActionEvent e) 
			{
				rearrange();
			}
		});
		
		saveResetPanel.add(saveButton, 		cc.xy(2, 1));
		saveResetPanel.add(reloadButton, 	cc.xy(4, 1));
		content.add(saveResetPanel, 		cc.xy(2, 2));
		/* **************************************** */
		
		// enables the save and reset buttons, if smth. was changed
		AbstractListener saveResetButtonListener = new AbstractListener() {
			
			public void actionPerformed (ActionEvent e) {
				enableButtons();
			}
			public void keyReleased(KeyEvent e) {
				enableButtons();
			}
			
			private void enableButtons () 
			{
				saveButton.setEnabled(true);
				reloadButton.setEnabled(true);
			}
		};

		/* **********  name:  ********** */
		nameField = new LimitTextField(40);
		content.add(new NamedComponent(
				Translatrix.getTranslationString("formeditor.name"),
				nameField), cc.xy(2, 4));
		nameField.addKeyListener(saveResetButtonListener);
		/* **************************************** */
		
		/* **********  version:  ********** */
		versionField = new LimitTextField(20);
		content.add(new NamedComponent(
				Translatrix.getTranslationString("formeditor.version"),
				versionField), cc.xy(2, 6));
		versionField.addKeyListener(saveResetButtonListener);
		/* **************************************** */
		
		/* **********  sub form only:  ********** */
		subformOnlyBox = new JCheckBox(
				Translatrix.getTranslationString("formeditor.subFormOnly"));
		subformOnlyBox.setToolTipText(
				Translatrix.getTranslationString("formeditor.onlyUsedAsSubform"));
		subformOnlyBox.setOpaque(false);
		content.add(subformOnlyBox, cc.xy(2, 8));
		subformOnlyBox.addActionListener(saveResetButtonListener);
		/* **************************************** */
		
		/* **********  description:  ********** */
		descriptionArea = new JTextArea();
		descriptionArea.setLineWrap(true);
		descriptionArea.setWrapStyleWord(true);
		content.add(new NamedComponent(
				Translatrix.getTranslationString("formeditor.description"),
				new JScrollPane(descriptionArea)), cc.xy(2, 10));
		descriptionArea.addKeyListener(saveResetButtonListener);
		/* **************************************** */
		
		/* **********  manage templates:  ********** */
		JButton manageTemplatesButton = new JButton (
				Translatrix.getTranslationString("formeditor.printTemplateDialog.managerTemplates"));
//				GECAMedModule.getSmallIcon(GECAMedIconNames.TEMPLATE));
		manageTemplatesButton.setToolTipText(
				Translatrix.getTranslationString("formeditor.printTemplateDialog.managerTemplates"));
		manageTemplatesButton.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent e)
			{
				openPrintTemplateDialog();
			}
		});
		content.add(manageTemplatesButton, cc.xy(2, 12));
		/* **************************************** */
	}
	
	
	public void rearrange () 
	{
		if (tabbedPane == null 
				|| templateList == null) 
		{
			this.tabbedPane 	= model.getView().getTabbedPane();
			this.templateList 	= model.getView().getTemplateList();
		}
		
		/* **************************************** */
		// the tab with the templates isn't selected 
		// or no template of this list is selected
		/* **************************************** */
		if (tabbedPane == null
				|| tabbedPane.getSelectedIndex() != FormEditorModule.LIST_TAB
				|| templateList == null
				|| templateList.getSelectedIndex() < 0) 
		{
			this.setVisible(false);
			return;
		}
		/* **************************************** */
		
		/* **************************************** */
		// create the settings for the selected template
		/* **************************************** */
		this.setVisible(true);
		
		currentTemplate 		= (FormTemplate) templateList.getSelectedValue();
		
		nameField.setText(currentTemplate.getName());
		versionField.setText(currentTemplate.getVersion());
		subformOnlyBox.setSelected(currentTemplate.isSubFormOnly());
		descriptionArea.setText(currentTemplate.getDescription());
		
		saveButton.setEnabled(false);
		reloadButton.setEnabled(false);
		
		this.validate();
		/* **************************************** */
	}
	
	
	
	/* ======================================== */
	// 		HELP METHODS
	/* ======================================== */
	
	private void saveTemplateSettings (ActionEvent e) 
	{
		FormManager manager = (FormManager) ManagerFactory.getRemote(FormManagerImpl.class);
		
		/* load the latest template, in case there were changes made, 
		 * while the template was loaded the last time
		 */
		currentTemplate = manager.getTemplate(currentTemplate.getId());
		
		// check the new name
		String name = nameField.getText();
		if (!model.isValidFormTemplateName(
				name, currentTemplate.getName())) 
		{
			name = model.getValidFormTemplateName(
					nameField.getText());
			if (name == null) {
				return;
			}
			nameField.setText(name);
		}
		
		currentTemplate.setName(name);
		currentTemplate.setVersion(versionField.getText());
		currentTemplate.setSubFormOnly(subformOnlyBox.isSelected());
		currentTemplate.setDescription(descriptionArea.getText());
		currentTemplate = manager.saveTemplateWithoutIReport(currentTemplate);
		
		FormModel formModel = model.getFormModel();
		if (formModel != null) 
		{
			FormTemplate template = formModel.getTemplate();
			if (template != null) 
			{
				template.setName(currentTemplate.getName());
				template.setVersion(currentTemplate.getVersion());
				template.setDescription(currentTemplate.getDescription());
				
				model.getView().updateTitle(currentTemplate.getName());
			}
		}
		
		saveButton.setEnabled(false);
		reloadButton.setEnabled(false);
		
		model.updateTemplateListModel();
		templateList.setSelectedValue(currentTemplate, true);
	}
	
	
	private void openPrintTemplateDialog()
	{
		if (printTemplateDialog == null)
			printTemplateDialog = new PrintTemplateDialog();
		
		currentTemplate = printTemplateDialog.show(currentTemplate);
		
		model.updateTemplateListModel();
		templateList.setSelectedValue(currentTemplate, true);
	}
}
