/*******************************************************************************
 * 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.prescription.gui.widgets.editor.template;



import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ScrollPaneConstants;
import javax.swing.border.LineBorder;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.undo.UndoManager;

import lu.tudor.santec.gecamed.core.gui.GECAMedColors;
import lu.tudor.santec.gecamed.core.gui.utils.UndoTextArea;
import lu.tudor.santec.gecamed.core.gui.utils.UndoTextField;
import lu.tudor.santec.gecamed.prescription.ejb.entity.beans.PrescriptionTemplate;
import lu.tudor.santec.gecamed.prescription.ejb.entity.beans.PrescriptionType;
import lu.tudor.santec.gecamed.prescription.ejb.entity.beans.TemplateDrug;
import lu.tudor.santec.gecamed.prescription.gui.widgets.drugbrowser.NameFilter;
import lu.tudor.santec.gecamed.prescription.gui.widgets.editor.EditorModel;
import lu.tudor.santec.i18n.Translatrix;

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


/**
 * The TemplatePanel shows the list of prescription templates for the current selected prescription type.
 * It show a small table with the short cut and the name of the template. After right-click on a template
 * a small preview of the content appears. a double click sends the template to the current prescription editor.
 * 
 * 
 * 
 * @author martin.heinemann@tudor.lu
 *
 *
 * @version
 * <br>$Log: TemplatePanel.java,v $
 * <br>Revision 1.9  2008-09-25 09:43:07  heinemann
 * <br>fixed copyrights
 * <br>
 * <br>Revision 1.8  2008-05-13 09:33:26  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.7  2008-01-15 13:40:35  heinemann
 * <br>better documentation
 * <br>
 * <br>Revision 1.6  2007/07/04 08:50:50  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.5  2007/03/30 12:18:00  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.4  2007/03/14 09:07:36  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.3  2007/03/12 14:33:58  heinemann
 * <br>Incomplete - # 5: Implement the filter function for the prescription templates
 * <br>http://santec.tudor.lu:8888/gecamed/ticket/5
 * <br>
 * <br>Revision 1.2  2007/03/02 08:28:39  hermen
 * <br>initial checkin after the merge of PatientModuleRebuild with the main HEAD
 * <br>
 * <br>Revision 1.1.2.8  2007/01/22 14:42:20  heinemann
 * <br>Complete - # 6: Antecedent prescription viewer
 * <br>http://santec.tudor.lu:8888/gecamed/ticket/6
 * <br>
 * <br>Revision 1.1.2.7  2007/01/11 12:09:59  heinemann
 * <br>Complete - # 51: Create preview for prescription templates
 * <br>http://santec.tudor.lu:8888/gecamed/ticket/51
 * <br>
 * <br>Revision 1.1.2.6  2007/01/11 10:41:13  heinemann
 * <br>Complete - # 51: Create preview for prescription templates
 * <br>http://santec.tudor.lu:8888/gecamed/ticket/51
 * <br>
 * <br>Revision 1.1.2.5  2006/12/28 10:32:26  heinemann
 * <br>bug fixing and template improvements
 * <br>
 * <br>Revision 1.1.2.4  2006/12/22 13:26:09  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.1.2.3  2006/12/21 14:26:43  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.1.2.2  2006/12/19 14:53:30  heinemann
 * <br>printing etc
 * <br>
 * <br>Revision 1.1.2.1  2006/12/14 09:34:01  heinemann
 * <br>many changes
 * <br>
 */
public class TemplatePanel extends JPanel {


	/* *****************************************************************
	 * Class members
	 */

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;


	protected JTable templateTable;


	private TemplateModel model;


	private UndoManager undoManager;


	protected UndoTextField filterTextField;


	private CellConstraints cc;


	private UndoTextArea textTextArea;


	private JPopupMenu pop;


	private NameFilter shortcutFilter;


	private JPanel mainPanel;

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

	/**
	 * @param model
	 * @param controler
	 */
	public TemplatePanel (TemplateModel model) {
		/* ====================================================== */
		this.model = model;
		/* ------------------------------------------------------- */
		this.setLayout(new BorderLayout(0, 2));
		this.setOpaque(false);
		/* ------------------------------------------------------- */
		initComponent();
		initFilterAction();
		/* ------------------------------------------------------- */
		// a label and a button in the header
		/* ------------------------------------------------------ */
		JPanel header = new JPanel(new BorderLayout());
		header.add(new JLabel(
				Translatrix.getTranslationString("prescription.name.templates") +":"),
				BorderLayout.CENTER);
		header.setOpaque(true);
		header.setBackground(GECAMedColors.c_GECAMedDarkerBackground);
		/* ------------------------------------------------------- */
//		this.setBorder(BorderFactory.createTitledBorder(
//				Translatrix.getTranslationString("prescription.name.templates")));
		/* ------------------------------------------------------- */
		this.add(header, 	BorderLayout.NORTH);
		this.add(mainPanel, BorderLayout.CENTER);
		/* ====================================================== */
	}

	/**
	 * init the components
	 */
	private void initComponent() {
		/* ============================================= */
		this.mainPanel = new JPanel();
		// set the FormLayout
		mainPanel.setLayout(new FormLayout(
				// cols
				"0dlu," +
				"fill:10dlu:grow," +
				"0dlu",
				// rows
				"0dlu," +
				"fill:pref," +
				"1dlu," +
				"fill:10dlu:grow," +
				"1dlu"));
		mainPanel.setOpaque(false);
		/* ------------------------------------------------------ */
		this.cc = new CellConstraints();

		this.undoManager = new UndoManager();
		/* ------------------------------------------------------ */
		// filter textfield
		this.filterTextField = new UndoTextField(undoManager);
		this.filterTextField.setToolTipText(Translatrix.getTranslationString("template.desc.filterToolTip"));

		mainPanel.add(filterTextField, cc.xy(2, 2));
		// the actions is added in the TemplateControler

		/* ------------------------------------------------------ */
		// table
		this.templateTable = new JTable();
		templateTable.setModel(model);
		// layout tweaks
		templateTable.getColumnModel().getColumn(0).setMinWidth(40);
		templateTable.getColumnModel().getColumn(0).setMaxWidth(40);

		templateTable.getTableHeader().setReorderingAllowed(false);

		templateTable.getColumnModel().getColumn(0).setCellRenderer(new TemplateCellRenderer(model));
		templateTable.getColumnModel().getColumn(1).setCellRenderer(new TemplateCellRenderer(model));


		templateTable.setColumnSelectionAllowed(false);
		templateTable.setRowSelectionAllowed(true);



		JScrollPane tScroll = new JScrollPane(templateTable);
		tScroll.getViewport().setOpaque(false);
		tScroll.setBackground(Color.WHITE);

		tScroll.setPreferredSize(new Dimension(220,
				tScroll.getPreferredSize().height));


		mainPanel.add(tScroll, cc.xy(2, 4));


		initTemplatePreview();
		/* ============================================= */
	}



	private void initFilterAction() {
		/* ================================================== */
		this.shortcutFilter = new NameFilter();
//		this.nameFilter = new NameFilter();
//		model.installFilter(this.shortcutFilter, 0);
//		model.installFilter(this.nameFilter, 1);
//		model.setFilteringEnabled(true, 0);
//		model.setFilteringEnabled(true, 1);


		this.filterTextField.getDocument().addDocumentListener(new DocumentListener() {

			public void changedUpdate(DocumentEvent e) {
				doAction();
			}

			public void insertUpdate(DocumentEvent e) {
				doAction();
			}

			public void removeUpdate(DocumentEvent e) {
				doAction();
			}

			private void doAction() {
				/* ================================================== */
				shortcutFilter.setFilter(filterTextField.getText());
//				nameFilter.setFilter(filterTextField.getText());
				model.update();
				model.fireTableDataChanged();
				/* ================================================== */
			}

		});
		/* ================================================== */
	}


	/* ****************************************************************
	 * ****************************************************************
	 * Template preview
	 */
	/**
	 * The preview is a window containing a textcomponent displaying the
	 * content of this prescription template.
	 * It is opened with a single click on thetemplate in the JTable
	 * We will use a timer to delay to delay the window in order to
	 * click an other template, for usability reasons.
	 *
	 * Window closes by click, esc, enter, focus lost
	 * @param temp
	 */
	public void showTemplatePreview(PrescriptionTemplate temp, MouseEvent e) {
		/* ====================================================== */
		if (pop != null && pop.isVisible()) {
			pop.setVisible(false);
			e.consume();
			return;
		}

		if (temp == null)
			return;
		/* ------------------------------------------------------ */

		if (PrescriptionType.MEDICINE.equals(
				EditorModel.getStringForTypeId(temp.getPrescriptionTypeId()))) {
					/* ------------------------------------------------------ */
					// Construct the drugs with the posology
					if (temp.getTemplateDrugs() != null) {
						/* ------------------------------------------------------ */
						StringBuffer sBuff = new StringBuffer();
						for(TemplateDrug d : temp.getTemplateDrugs()) {
							sBuff.append(d.getName());
							sBuff.append("\n");
							sBuff.append((d.getPosology() != null && !"".equals(d.getPosology())
											? d.getPosology()+"\n\n" : "\n\n"));
						}
						this.textTextArea.setText(sBuff.toString());
						/* ------------------------------------------------------ */
					}
					/* ------------------------------------------------------ */
				}
		else
			this.textTextArea.setText(temp.getTextContent());
		pop.show(this, this.templateTable.getWidth()+15, 1);

		/* ====================================================== */
	}

	public void hideTemplatePreview() {
		/* ====================================================== */
		pop.setVisible(false);
		/* ====================================================== */
	}


	/**
	 * Init the template preview
	 */
	private void initTemplatePreview() {
		/* ====================================================== */
		this.textTextArea = new UndoTextArea(new UndoManager());
		this.textTextArea.setLineWrap(true);
		this.textTextArea.setWrapStyleWord(true);
//		this.textTextArea.getDocument().addDocumentListener(this);

		this.textTextArea.setEditable(false);
		this.textTextArea.setFocusable(false);

		/* ------------------------------------------------------ */
		JScrollPane tScroll = new JScrollPane(textTextArea);
		tScroll.setVerticalScrollBarPolicy(
				ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
		/* ------------------------------------------------------ */

		this.pop = new JPopupMenu();

		pop.setLayout(new BorderLayout());

		pop.add(tScroll);
		pop.setPreferredSize(new Dimension(400, 300));

		pop.add(new JLabel("QuickPreview "), BorderLayout.NORTH);
		pop.setBorder(new LineBorder(Color.BLACK));


		pop.addKeyListener(new KeyAdapter() {

			/* (non-Javadoc)
			 * @see java.awt.event.KeyAdapter#keyPressed(java.awt.event.KeyEvent)
			 */
			@Override
			public void keyPressed(KeyEvent e) {
				/* ============================================= */
				pop.setVisible(false);
				e.consume();
				/* ============================================= */
			}

		});

		textTextArea.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				/* ============================================= */
				pop.setVisible(false);
				e.consume();
				/* ============================================= */
			}
		});
		textTextArea.addKeyListener(new KeyAdapter() {
			@Override
			public void keyPressed(KeyEvent e) {
				/* ============================================= */
				pop.setVisible(false);
				e.consume();
				/* ============================================= */
			}
		});

		pop.pack();
		/* ====================================================== */
	}


}
