/*******************************************************************************
 * 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.templatelist;

import java.awt.Color;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.text.DateFormat;
import java.util.Locale;

import javax.swing.GrayFilter;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JToggleButton;
import javax.swing.border.LineBorder;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;

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.controller.ControllerConfig;
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.components.ComboBoxTypeModel;
import lu.tudor.santec.gecamed.letter.gui.components.LimitedTextArea;
import lu.tudor.santec.i18n.Translatrix;

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

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

/*
 * A panel that shows teh details of a template
 */

public class TemplateDetailsPanel extends JPanel 
{
	/* ======================================== */
	// 		CONSTANTS
	/* ======================================== */
	
	private static final long serialVersionUID = 1L;
	
	public static final int DESC_MAX_LENGTH = 300;
	
	
	
	/* ======================================== */
	// 		MEMBERS
	/* ======================================== */
	
	/** the logger Object for this class */
	private static Logger logger = Logger.getLogger(TemplateDetailsPanel.class.getName());
	
	private static DateFormat dateFormatter = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.getDefault());
	
	
	private JTextField nameField;
	
	private JTextArea descArea;
	
	private JTextField createdOnField;
	
	private JTextField modifiedOnField;
	
	private JTextField mimeTypeField;
	
	private JTextField createdByField;
	
	private JTextField modifiedByField;
	
	private JComboBox typeBox;
	
	private JToggleButton privateBox;
	
	private ComboBoxTypeModel cbModel;
	
	private boolean adapting;
	
	private LetterTemplate currentTemplate;
	
	
	
	/* ======================================== */
	// 		CONSTRUCTORS
	/* ======================================== */
	
	public TemplateDetailsPanel () 
	{
		this.setLayout(new FormLayout("5px, l:p, 5px, f:d:g, 5px", 
				"5px,f:p," +	// name
				"5px,f:p," +	// type
				"5px,f:125px," +	// description
				"5px,f:p," +	// document mime type
				"5px,f:p," +	// created by
				"5px,f:p," +	// created date
				"5px,f:p," +	// last modified by
				"5px,f:p," +	// last modified date
				"5px,f:p," +	// private
				"5px:g"));
		
		this.setBorder(new LineBorder(Color.LIGHT_GRAY, 1));
		this.setOpaque(false);
		
		CaretListener caretListener = new CaretListener()
		{
			public void caretUpdate(CaretEvent e)
			{
				if (adapting)
					return;
				
				JComponent source = (JComponent) e.getSource();
				
				
				if (currentTemplate != null)
				{
					if (source == nameField
							&& !nameField.getText().equals(currentTemplate.getName()))
						setModified(true);
					else if (source == descArea
							&& !descArea.getText().equals(currentTemplate.getDescription()))
						setModified(true);
				}
			}
		};
		
		ItemListener itemListener = new ItemListener()
		{
			public void itemStateChanged(ItemEvent e)
			{
				if (adapting)
					return;
				
				setModified(true);
			}
		};
		
		// name
		JLabel nameLabel = new JLabel(Translatrix
				.getTranslationString("LetterTemplateModule.details.name"));
		nameField = new JTextField();
		nameField.addCaretListener(caretListener);
		
		// created on
		JLabel createdOnLabel = new JLabel(
				Translatrix.getTranslationString("LetterTemplateModule.details.created_on"));
		createdOnField = new JTextField();
		createdOnField.setEnabled(false);
		
		// created BY
		JLabel createdByLabel = new JLabel(
				Translatrix.getTranslationString("LetterTemplateModule.details.created_by"));
		createdByField = new JTextField();
		createdByField.setEnabled(false);
		
		// modified on
		JLabel modifiedOnLabel = new JLabel(
				Translatrix.getTranslationString("LetterTemplateModule.details.modified_on"));
		modifiedOnField = new JTextField();
		modifiedOnField.setEnabled(false);
		
		// modified by
		JLabel modifiedByLabel = new JLabel(
				Translatrix.getTranslationString("LetterTemplateModule.details.modified_by"));
		modifiedByField = new JTextField();
		modifiedByField.setEnabled(false);
		
		// MIME type
		JLabel mimeTypeLabel = new JLabel(
				Translatrix.getTranslationString("LetterTemplateModule.details.mimetype"));
		mimeTypeField = new JTextField();
		mimeTypeField.setEnabled(false);
		
		// template type
		JLabel typeLabel = new JLabel(
				Translatrix.getTranslationString("LetterTemplateModule.details.type"));
		
		cbModel = new ComboBoxTypeModel();
		cbModel.queryAllTemplateTypes();
//		cbModel	= LetterTemplateModule.getInstance().getCbModel();
		typeBox = new JComboBox(cbModel);
		typeBox.setEditable(true);
		typeBox.addItemListener(itemListener);
		
		// is private 
		JLabel privateLabel = new JLabel(
				Translatrix.getTranslationString("LetterTemplateModule.details.private"));
		privateBox = new JToggleButton();
		privateBox.setOpaque(false);
		privateBox.addItemListener(itemListener);
		
		ImageIcon selectedIcon		= GECAMedModule.getIcon(GECAMedIconNames.ENTRY_PRIVATE);
		ImageIcon defaultIcon		= GECAMedModule.getIcon(GECAMedIconNames.ENTRY_PUBLIC);
		privateBox.setIcon(defaultIcon);
		privateBox.setSelectedIcon(selectedIcon);
		privateBox.setDisabledIcon(new ImageIcon(GrayFilter.createDisabledImage(defaultIcon.getImage())));
//		privateBox.setDisabledSelectedIcon(new ImageIcon(GrayFilter.createDisabledImage(selectedIcon.getImage())));
		
		// description
		JLabel descLabel = new JLabel(
				Translatrix.getTranslationString("LetterTemplateModule.details.description"));
		descArea = new LimitedTextArea(DESC_MAX_LENGTH);
		descArea.addCaretListener(caretListener);
		descArea.setWrapStyleWord(true);
		JScrollPane descScroller = new JScrollPane(descArea);
		
		
		// ADD COMPONENTS
		CellConstraints cc = new CellConstraints();
		int row = 0;
		
		this.add(nameLabel,			cc.xy(2, row+=2));
		this.add(nameField,			cc.xy(4, row));
		this.add(typeLabel,			cc.xy(2, row+=2));
		this.add(typeBox,			cc.xy(4, row));
		this.add(descLabel,			cc.xy(2, row+=2, CellConstraints.LEFT, CellConstraints.TOP));
		this.add(descScroller,		cc.xy(4, row));
		this.add(mimeTypeLabel,		cc.xy(2, row+=2));
		this.add(mimeTypeField,		cc.xy(4, row));
		this.add(createdByLabel,	cc.xy(2, row+=2));
		this.add(createdByField,	cc.xy(4, row));
		this.add(createdOnLabel,	cc.xy(2, row+=2));
		this.add(createdOnField,	cc.xy(4, row));
		this.add(modifiedByLabel,	cc.xy(2, row+=2));
		this.add(modifiedByField,	cc.xy(4, row));
		this.add(modifiedOnLabel,	cc.xy(2, row+=2));
		this.add(modifiedOnField,	cc.xy(4, row));
		this.add(privateLabel,		cc.xy(2, row+=2));
		this.add(privateBox,		cc.xy(4, row, CellConstraints.LEFT, CellConstraints.FILL));
	}
	
	
	
	/* ======================================== */
	// 		CLASS BODY
	/* ======================================== */
	
	@SuppressWarnings("static-access")
	public void render(LetterTemplate template)
	{
		adapting = true;
		currentTemplate = template;
		
		try
		{
			if (template != null) 
			{
				// name
				nameField.setEnabled(true);
				if (template.getName() != null)
					 nameField.setText(template.getName());
				else nameField.setText("");
				
				// description
				descArea.setEnabled(true);
				if (template.getDescription() != null)
					 descArea.setText(template.getDescription());
				else descArea.setText("");
				
				// type
				typeBox.setEnabled(true);
				typeBox.setSelectedItem(template.getType());
				
				// is private
				privateBox.setEnabled(true);
				if (template.getShare() != null)
					 privateBox.setSelected(!template.getShare());
				else privateBox.setSelected(false);
				
				privateBox.setEnabled(GECAMedModule.getCurrentPhysician().getId()
						.equals(currentTemplate.getCreatedBy()));
				
				// MIME type
				if (template.getMimetype().equalsIgnoreCase(ControllerConfig.MIME_WORD)) 
				{
					mimeTypeField.setText(
							Translatrix.getTranslationString("LetterTemplateModule.tps.WORD"));
				} 
				else if (template.getMimetype().equalsIgnoreCase(ControllerConfig.MIME_WRITER)) 
				{
					mimeTypeField.setText(
							Translatrix.getTranslationString("LetterTemplateModule.tps.WRITER"));
				}
				else 
				{
					mimeTypeField.setText("N/A");
				}
				
				// created on
				if (template.getCreatedOn() != null)
					 createdOnField.setText(dateFormatter.format(template.getCreatedOn()));
				else createdOnField.setText("");
				
				// modified on
				if (template.getModifiedOn() != null)
					 modifiedOnField.setText(dateFormatter.format(template.getModifiedOn()));
				else modifiedOnField.setText("");
				
				// modified by
				if (template.getModifiedBy() != null)
					modifiedByField.setText(MainFrame.getInstance().getPhysicianById(
							template.getModifiedBy()).getMnemonic());
				else 
					modifiedByField.setText("");
				
				// created by
				if (template.getCreatedBy() != null)
				{
					createdByField.setText(MainFrame.getInstance().getPhysicianById(
							template.getCreatedBy()).getMnemonic());
				}
				else
				{
					createdByField.setText("");
				}
			}
			else 
			{
				nameField.setText("");
				nameField.setEnabled(false);
				descArea.setText("");
				descArea.setEnabled(false);
				typeBox.setSelectedIndex(-1);
				typeBox.setEnabled(false);
				privateBox.setSelected(false);
				privateBox.setEnabled(false);
				createdByField.setText("");
				createdOnField.setText("");
				modifiedByField.setText("");
				modifiedOnField.setText("");
				mimeTypeField.setText("");
			}
		}
		catch (Throwable e)
		{
			logger.log(Level.ERROR, "Error while setting the properties of template " + 
					(template == null ? "" : template.getName()), e);
		}
		finally
		{
			adapting = false;
		}
	}
	
	
	public ComboBoxTypeModel getCbModel() 
	{
		return cbModel;
	}
	
	
//	public void setCbModel(ComboBoxTypeModel cbModel) 
//	{
//		this.cbModel = cbModel;
//	}
	
	
	public LetterTemplate getChangedTemplate ()
	{
		currentTemplate.setName(nameField.getText());
		currentTemplate.setDescription(descArea.getText());
		currentTemplate.setShare(!privateBox.isSelected());
		currentTemplate.setType((String) typeBox.getSelectedItem());
		
		return currentTemplate;
	}
	
	
	public LetterTemplate getCurrentTemplate ()
	{
		return currentTemplate;
	}
	
	
//	private boolean isModified ()
//	{
//		if (currentTemplate == null)
//			return false;
//		else if (((currentTemplate.getName() == null && nameField.getText().length() == 0)
//						|| currentTemplate.getName().equals(nameField.getText()))
//				&& ((currentTemplate.getDescription() == null && descArea.getText().length() == 0) 
//						|| currentTemplate.getDescription().equals(descArea.getText()))
//				&& ((currentTemplate.getShare() == null && privateBox.isSelected())
//						|| currentTemplate.getShare().booleanValue() == !privateBox.isSelected())
//				&& ((currentTemplate.getType() == null && (typeBox.getSelectedItem() == null 
//								|| ((String)typeBox.getSelectedItem()).length() == 0))
//						|| currentTemplate.getType().equals(typeBox.getSelectedItem())))
//			return false;
//		else 
//			return true;
//	}
	
	
	private void setModified (boolean modified)
	{
		if (!adapting)
			LetterTemplateModule.getInstance().setModified(modified);
	}
}
