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

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
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 java.text.DateFormat;

import javax.swing.DefaultListCellRenderer;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;
import javax.swing.border.LineBorder;
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.prescription.ejb.entity.beans.Prescription;
import lu.tudor.santec.gecamed.prescription.ejb.entity.beans.PrescriptionDrug;
import lu.tudor.santec.gecamed.prescription.ejb.entity.beans.PrescriptionType;
import lu.tudor.santec.gecamed.prescription.gui.PrescriptionIcons;
import lu.tudor.santec.gecamed.prescription.gui.widgets.editor.EditorModel;
import lu.tudor.santec.i18n.Translatrix;

/**
 * This panel shows ancient prescription of the current patient.
 * It is placed under the template list.
 * There is a controler called AntecedentControler that is responsible for loading
 * and any further interactions on the list.
 * 
 * 
 * @author martin.heinemann@tudor.lu
 *
 *
 * @version
 * <br>$Log: AntecedentPanel.java,v $
 * <br>Revision 1.12  2010-03-30 10:39:42  troth
 * <br>Redesign of the prescription view - change icon manager class
 * <br>
 * <br>Revision 1.11  2008-09-25 09:43:08  heinemann
 * <br>fixed copyrights
 * <br>
 * <br>Revision 1.10  2008-07-23 15:13:57  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.9  2008-05-13 09:33:26  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.8  2008-01-15 13:40:35  heinemann
 * <br>better documentation
 * <br>
 * <br>Revision 1.7  2007-10-22 09:58:13  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.6  2007/07/05 08:22:49  hermen
 * <br>small gui improvements
 * <br>
 * <br>Revision 1.5  2007/07/04 08:50:50  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.4  2007/03/12 14:51:39  heinemann
 * <br>humilation
 * <br>
 * <br>Revision 1.3  2007/03/12 14:32:10  heinemann
 * <br>Complete - # 46: make printed prescriptions editable
 * <br>http://santec.tudor.lu:8888/gecamed/ticket/46
 * <br>
 * <br>Revision 1.2  2007/03/02 08:28:44  hermen
 * <br>initial checkin after the merge of PatientModuleRebuild with the main HEAD
 * <br>
 * <br>Revision 1.1.2.7  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.6  2007/01/22 10:24:07  heinemann
 * <br>Incomplete - # 13: print copies of prescriptions
 * <br>http://santec.tudor.lu:8888/gecamed/ticket/13
 * <br>
 * <br>Revision 1.1.2.5  2007/01/11 13:42:11  heinemann
 * <br>Complete - # 21: Context Menu -> create new prescription
 * <br>http://santec.tudor.lu:8888/gecamed/ticket/21
 * <br>
 * <br>sysout removed
 * <br>
 * <br>Revision 1.1.2.4  2007/01/11 08:37:16  heinemann
 * <br>Complete - # 48: Change lable "Antecedents" to "Ordnonnance"
 * <br>http://santec.tudor.lu:8888/gecamed/ticket/48
 * <br>
 * <br>Revision 1.1.2.3  2007/01/04 13:51:37  heinemann
 * <br>The great space cleaning lady has done a big bunch of refactoring
 * <br>
 * <br>Revision 1.1.2.2  2006/12/22 13:18:09  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.1.2.1  2006/12/14 09:34:01  heinemann
 * <br>many changes
 * <br>
 */
public class AntecedentPanel extends JPanel {

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;
	protected JButton openButten;
	private JList list;
	private Integer incidentId;
	private JPopupMenu popup;
	private UndoTextArea textTextArea;
	private JPopupMenu quickPreview;

	/**
	 *
	 */
	public AntecedentPanel() {
		/* ====================================================== */
		initComponent();
		/* ====================================================== */
	}

	/**
	 * Init the componentents
	 */
	private void initComponent() {
		/* ============================================= */
		this.setLayout(new BorderLayout(0, 2));
		this.setOpaque(false);
		/* ------------------------------------------------------ */
		// a label and a button in the header
		JPanel header = new JPanel(new BorderLayout());
		header.add(new JLabel(
				Translatrix.getTranslationString("prescription.name.ordonnance") +":"),
				BorderLayout.CENTER);
//		header.setBackground(Color.WHITE);
		header.setOpaque(true);
		header.setBackground(GECAMedColors.c_GECAMedDarkerBackground);

		// the button
//		this.openButten = new JButton(IconBuilder.getMiniIcon(IconBuilder.ANTECEDENT));
//		this.openButten.setEnabled(false);
//		this.openButten.setToolTipText("Will be available in later versions");
//		openButten.setMargin(new java.awt.Insets(0, 0, 0, 0));
//
//		header.add(openButten, BorderLayout.EAST);
		/* ------------------------------------------------------ */
		// add
		this.add(header, BorderLayout.NORTH);

		/* ------------------------------------------------------ */
		initList();
		/* ------------------------------------------------------ */
		// popup
		this.popup = new JPopupMenu();
		initPrescriptionQuickPreview();

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

	public JPopupMenu getPopup() {
		/* ====================================================== */
		return this.popup;
		/* ====================================================== */
	}


	/**
	 * Init the JList
	 */
	private void initList() {
		/* ============================================= */
		this.list = new JList();

		JScrollPane lScroll = new JScrollPane(list);

		this.add(lScroll, BorderLayout.CENTER);

		// set a renderer
		list.setCellRenderer(new PrescriptionCellRenderer());
		/* ============================================= */
	}

	/**
	 *
	 * Return the JList to add functionality to it
	 *
	 * @return
	 */
	public JList getList() {
		/* ====================================================== */
		return this.list;
		/* ====================================================== */
	}

	/**
	 * Set the current incident id for rendering improvements
	 *
	 * @param incidentId
	 */
	public void setIncidentId(Integer incidentId) {
		/* ============================================= */
		this.incidentId = incidentId;
		/* ============================================= */
	}





	/**
	 * Init the template preview
	 */
	private void initPrescriptionQuickPreview() {
		/* ====================================================== */
//		this.textPanel = new JPanel(new BorderLayout());
		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.quickPreview = new JPopupMenu();
		quickPreview.setLayout(new BorderLayout());
		quickPreview.add(tScroll);
		quickPreview.setPreferredSize(new Dimension(400, 200));


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


		quickPreview.addKeyListener(new KeyAdapter() {

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

		});

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

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




	/* ****************************************************************
	 * ****************************************************************
	 * 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 showQuickPreview(Prescription temp, MouseEvent e) {
		/* ====================================================== */
		if (quickPreview != null && quickPreview.isVisible()) {
			quickPreview.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.getPrescriptionDrugs() != null) {
						/* ------------------------------------------------------ */
						StringBuffer sBuff = new StringBuffer();
						for(PrescriptionDrug d : temp.getPrescriptionDrugs()) {
							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());
		quickPreview.show(this, this.list.getWidth()+15, -30);

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

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






	/**
	 * @author martin.heinemann@tudor.lu
	 * 23.07.2008
	 * 13:39:25
	 *
	 *
	 * @version
	 * <br>$Log: AntecedentPanel.java,v $
	 * <br>Revision 1.12  2010-03-30 10:39:42  troth
	 * <br>Redesign of the prescription view - change icon manager class
	 * <br>
	 * <br>Revision 1.11  2008-09-25 09:43:08  heinemann
	 * <br>fixed copyrights
	 * <br>
	 * <br>Revision 1.10  2008-07-23 15:13:57  heinemann
	 * <br>*** empty log message ***
	 * <br>
	 *   
	 */
	class PrescriptionCellRenderer extends DefaultListCellRenderer {

		private static final long serialVersionUID = 1L;

		private boolean usePink = false;

		private Color pinkDark = new Color(252,223,223);
		private Color pinkLight = new Color(252,224,224);
		private Color c_OddColor = new Color (237,243,254);
		private Color c_EvenColor = new Color (255,255,255);
		
		private ImageIcon chronicIcon = PrescriptionIcons.getSmallIcon(PrescriptionIcons.CHRONIC);
		
		
		JLabel label = new JLabel();

//		private DateFormat formater = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT);
		private DateFormat formater = DateFormat.getDateInstance(DateFormat.SHORT);
		/* (non-Javadoc)
		 * @see javax.swing.DefaultListCellRenderer#getListCellRendererComponent(javax.swing.JList, java.lang.Object, int, boolean, boolean)
		 */
		@Override
		public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
			/* ============================================= */
			if (value instanceof Prescription) {
				/* ------------------------------------------------------- */
				Prescription p = (Prescription) value;
				try {
					/* ------------------------------------------------------- */
					// format the date
					/* ------------------------------------------------------- */
					super.getListCellRendererComponent(
							list,
							formater.format(p.getPrescriptionDate()),
							index,
							isSelected,
							cellHasFocus);
					/* ------------------------------------------------------- */
				} catch (Exception e) {
					/* ------------------------------------------------------- */
					// if the formatter fails, we print "NO DATE!!"
					/* ------------------------------------------------------- */
					super.getListCellRendererComponent(
							list,
							"NO DATE!!",
							index,
							isSelected,
							cellHasFocus);
					/* ------------------------------------------------------- */
				}
				
				/* ------------------------------------------------------- */
				// handle the background color
				/* ------------------------------------------------------- */
				if (p.getIncidentId() != null)
					if (p.getIncidentId().equals(incidentId)) {
						/* ------------------------------------------------------ */
						// use the pink background
						usePink = true;
						/* ------------------------------------------------------ */
					} else {
						/* ------------------------------------------------------ */
						// use the blue background
						usePink = false;
						/* ------------------------------------------------------ */
					}
				/* ------------------------------------------------------- */
				// set the chronic icon
				/* ------------------------------------------------------- */
				if (p.getIsChronic() != null && p.getIsChronic() == true) {
					/* ------------------------------------------------------- */
					super.setIcon(chronicIcon);
					/* ------------------------------------------------------- */
				} else {
					super.setIcon(null);
				}
			} else {
				/* ------------------------------------------------------- */
				super.getListCellRendererComponent(list, value, index, isSelected,
					cellHasFocus);
				/* ------------------------------------------------------- */
			}
			
			/* ------------------------------------------------------- */
			// now set the background color
			/* ------------------------------------------------------- */
			Color	l_Background;
			if (usePink) {
				/* ------------------------------------------------------- */
				l_Background = ( index % 2 == 0) ? pinkDark : pinkLight;
				/* ------------------------------------------------------- */
			}
			else
				l_Background = ( index % 2 == 0) ? c_OddColor : c_EvenColor;

			if (isSelected)
				 this.setBackground(list.getSelectionBackground());
			else this.setBackground(l_Background);

		      return this;
			
			
			
//			/* ------------------------------------------------------- */
//			if (value instanceof Prescription) {
//				Prescription p = (Prescription) value;
//				try {
//					super.getListCellRendererComponent(
//							list,
//							formater.format(p.getPrescriptionDate()),
//							index,
//							isSelected,
//							cellHasFocus);
//				} catch (Exception e) {
//					super.getListCellRendererComponent(
//							list,
//							"NO DATE!!",
//							index,
//							isSelected,
//							cellHasFocus);
//				}
//			} else
//				super.getListCellRendererComponent(list, value, index, isSelected,
//					cellHasFocus);
//
//			
//
//			/* ------------------------------------------------------ */
//			if (value instanceof Prescription) {
//				Prescription p = (Prescription) value;
//				if (p.getIncidentId() != null)
//					if (p.getIncidentId().equals(incidentId)) {
//						/* ------------------------------------------------------ */
//						// use the pink background
//						usePink = true;
//						/* ------------------------------------------------------ */
//					} else {
//						/* ------------------------------------------------------ */
//						// use the blue background
//						usePink = false;
//						/* ------------------------------------------------------ */
//					}
//			}
//			/* ------------------------------------------------------ */
//			if (usePink) {
//				l_Background = ( index % 2 == 0) ? pinkDark : pinkLight;
//			}
//			else
//				l_Background = ( index % 2 == 0) ? c_OddColor : c_EvenColor;
//
//			if (isSelected)
//				 this.setBackground(list.getSelectionBackground());
//			else this.setBackground(l_Background);
//
//		      return this;
			/* ============================================= */
		}

	}






}
