/*****************************************************************************
 *                                                                           *
 *  Copyright (c) 2010 by SANTEC/TUDOR www.santec.tudor.lu                   *
 *                                                                           *
 *                                                                           *
 *  This library is free software; you can redistribute it and/or modify it  *
 *  under the terms of the GNU Lesser General Public License as published    *
 *  by the Free Software Foundation; either version 2 of the License, or     *
 *  (at your option) any later version.                                      *
 *                                                                           *
 *  This software 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 along with this library; if not, write to the Free Software      *
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA  *
 *                                                                           *
 *****************************************************************************/
package lu.tudor.santec.gecamed.patient.gui.memo;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.text.DateFormat;
import java.util.Collection;
import java.util.Date;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.SwingConstants;

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.widgets.GECAMedBaseDialog;
import lu.tudor.santec.gecamed.patient.ejb.entity.beans.Patient;
import lu.tudor.santec.gecamed.patient.ejb.entity.beans.PatientMemo;
import lu.tudor.santec.gecamed.patient.gui.PatientManagerModule;
import lu.tudor.santec.gecamed.patient.gui.simpleview.OverviewPanel;
import lu.tudor.santec.i18n.Translatrix;

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

/**
 * Dialog to show and manipulate memos.
 * It is opened by the SimpleViewPanel when the user clicks on the memo icon.
 * The dialog contains a list with the content of the memos attached to the current patient.
 * 
 * To create or modify memos it calls the MemoControler vom patient.gui.memo package
 * 
 * @author martin.heinemann@tudor.lu
 * 03.10.2007
 * 16:21:55
 *
 *
 * @version
 * <br>$Log: SimpleMemoView.java,v $
 * <br>Revision 1.3  2010-10-19 14:37:15  troth
 * <br>rename class SimpleViewPanel in OverviewPanel
 * <br>
 * <br>Revision 1.2  2010-03-24 18:46:56  troth
 * <br>Redesign of the patient view history - SimpleMemoView extends now from GECAMedBaseDialog
 * <br>
 * <br>Revision 1.1  2010-03-23 15:17:19  troth
 * <br>Redesign of the patient view history
 * <br>
 * <br>Revision 1.4  2008-09-25 09:43:06  heinemann
 * <br>fixed copyrights
 * <br>
 * <br>Revision 1.3  2008-01-21 14:58:42  heinemann
 * <br>code cleanup and java doc
 * <br>
 * <br>Revision 1.2  2007-10-22 09:58:14  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.1  2007-10-16 08:23:26  heinemann
 * <br>*** empty log message ***
 * <br>
 *   
 */
public class SimpleMemoView extends GECAMedBaseDialog implements ActionListener, MouseListener, PropertyChangeListener {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private static final Dimension c_PreferredSize = new Dimension(600, 400);
	
	private static final DateFormat formater = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT);
	
	private static final String CMD_ADD_MEMO = "addMemo";
	
	private static final String CMD_CLOSE    = "close_windows";
	
	private static final int MAX_WIDTH = 500;

	private static final String CMD_REMOVE_MEMO = "removeMemo";
	
	
	private Collection<PatientMemo> memos;

	private Patient patient;

	private JScrollPane scroll;

	private JPanel viewPanel;

	private CellConstraints cc;

	private int row;
	
	private FormLayout layout;

	private JButton addButton;

	private OverviewPanel simpleViewPanel;

	private JPopupMenu popup;

	private MemoItem lastClickedItem;

	private MemoControler memoControler;

	private JButton removeButton;
	
	/**
	 * 
	 */
	public SimpleMemoView(MemoControler mControler, OverviewPanel simpleViewPanel) {
		/* ================================================== */
		super(Translatrix.getTranslationString("PatientMemo.MemoTab"), true ,false);
		/* ------------------------------------------------------- */
		this.memoControler = mControler;
		memoControler.addPropertyChangeListener(this);
		this.simpleViewPanel = simpleViewPanel;
		initComponent();
		/* ================================================== */
	}
	
	
	/**
	 * @param b
	 */
	public void showDialog(boolean b) {
		/* ================================================== */
		if (b) {
			/* ------------------------------------------------------- */
			if (memoControler.getMemoCount() < 1L)
				if (!addMemo())
					return;
//			if (!loadMemos())
//				return;
			setMemos(memoControler.getMemos());
			adjustSize();
			
			MainFrame.showDialogCentered(this);
			/* ------------------------------------------------------- */
		} else
			this.setVisible(false);
		/* ================================================== */
	}
	
	private void adjustSize() {
		/* ================================================== */
		this.pack();
		
		int height = this.getHeight();
		if (height > 600)
			height = 550;
		this.setSize(MAX_WIDTH, height);
		/* ================================================== */
	}
	
	
	/**
	 * @param memos
	 */
	public void setMemos(Collection<PatientMemo> memos) {
		/* ================================================== */
		this.memos = memos;
		/* ------------------------------------------------------- */
		// update the view
		this.setTitle(Translatrix.getTranslationString("PatientMemo.MemoTab") + " - "
				+ Translatrix.getTranslationString("pm.patient")+": " 
				+ patient.toShortString());
		/* ------------------------------------------------------- */
		viewPanel.removeAll();
		this.layout = new FormLayout("fill:pref:grow", "0dlu");
		viewPanel.setLayout(this.layout);
		row = 2;
		// create memos
		if (this.memos != null) {
			/* ------------------------------------------------------- */
			for (PatientMemo p : this.memos) {
				MemoItem m = new MemoItem(p);
//				m.setPreferredSize(new Dimension(MAX_WIDTH, m.getPreferredSize().height));
				m.addMouseListener(this);
				
				this.layout.appendRow(new RowSpec("fill:pref"));
				this.layout.appendRow(new RowSpec("1dlu"));
				viewPanel.add(m, cc.xy(1, row));
				row += 2;
			}
			viewPanel.validate();
			viewPanel.updateUI();
			/* ------------------------------------------------------- */
		}
		/* ================================================== */
	}
	
	
	/**
	 * 
	 */
	private void initComponent() {
		// -------------------------------------------------------
		// create a panel for the memoviews
		this.layout = new FormLayout("fill:pref:grow", "0dlu");
		
		this.viewPanel = new JPanel(this.layout);
		viewPanel.setBackground(new Color(184, 207, 229));
		
		
		this.cc = new CellConstraints();
		this.row = 2;
		
		this.scroll = new JScrollPane(viewPanel);
			
		this.addButton = OverviewPanel.createButton(
				GECAMedModule.getMediumIcon(GECAMedIconNames.ADD_LINE),
				CMD_ADD_MEMO, this);
		
		this.removeButton = OverviewPanel.createButton(
				GECAMedModule.getMediumIcon(GECAMedIconNames.REMOVE_LINE),
				CMD_REMOVE_MEMO, this);
		
		
		this.okButton.addActionListener(this);
		
		this.add(scroll);
		this.addButton(addButton);
		this.addButton(removeButton);
		this.setSize(c_PreferredSize);
		
		
		/* ------------------------------------------------------- */
		// ====================================================================
		// init the mouse popup
		// ====================================================================
		this.popup = new JPopupMenu();
		
		JMenuItem addMemo = new JMenuItem(
				Translatrix.getTranslationString("PatientMemoEditorPanel.AddMemoButton"),
				GECAMedModule.getSmallIcon (GECAMedIconNames.ADD_LINE));
		/* ------------------------------------------------------ */
		addMemo.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				/* ============================================= */
				addMemo();
				/* ============================================= */
			}
		});
		popup.add(addMemo);
		popup.add(new JSeparator());
		
		JMenuItem delete = new JMenuItem(
				Translatrix.getTranslationString("PatientMemoEditorPanel.RemoveMemoButton"),
				GECAMedModule.getSmallIcon (GECAMedIconNames.REMOVE_LINE));
		/* ------------------------------------------------------ */
		delete.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				/* ============================================= */
				deleteMemo((MemoItem) lastClickedItem);
				/* ============================================= */
			}
		});
		popup.add(delete);
		/* ================================================== */
	}
	
	
	public void setPatient(Patient patient) {
		/* ================================================== */
		this.patient = patient;
		/* ================================================== */
	}

//	@SuppressWarnings("unchecked")
//	private boolean loadMemos() {
//		/* ================================================== */
//		if (this.patient == null)
//			return false;
//		/* ------------------------------------------------------- */
//		PatientMemoInterface mManager = (PatientMemoInterface) 
//				ManagerFactory.getManager(ManagerFactory.MEMOMANAGER);
//		/* ------------------------------------------------------- */
//		try {
//			List<PatientMemo> col = (ArrayList) mManager.getMemosByPatientID(patient.getId());
//			if (col != null && col.size() > 0) {
//				// reverse list
//				Collections.reverse(col);
//				setMemos(col);
//			}
//			else {
//				if (!addMemo())
//					return false;
//			}
//			viewPanel.validate();
//			viewPanel.updateUI();
//		} catch (Exception e1) {
//			e1.printStackTrace();
//			return false;
//		}
//		return true;
//		/* ================================================== */
//	}
	
	private boolean addMemo() {
		/* ================================================== */
		PatientMemo	l_Memo;

		l_Memo = new PatientMemo ();
		l_Memo.setCreationDate(new Date ());
		l_Memo.setAuthor(GECAMedModule.getCurrentUser());
		l_Memo.setPatientID(patient.getId());

		PatientMemoDialog dialog = new PatientMemoDialog();
		dialog.showMemoDialog(l_Memo);
		
		if (memoControler.addMemo(l_Memo)) {
			/* ------------------------------------------------------- */
			simpleViewPanel.updateField(OverviewPanel.CMD_MEMOWARNING);
			
			return true;
			/* ------------------------------------------------------- */
		} else
			return false;
		/* ================================================== */
	}
	
	private boolean deleteMemo(MemoItem memo) {
		/* ================================================== */
//		patientPanel.getMemoPanel().deleteMemo(memo.getMemo());
		memoControler.deleteMemo(memo.getMemo());
//		loadMemos();
		simpleViewPanel.updateField(OverviewPanel.CMD_MEMOWARNING);
		return true;
		/* ================================================== */
	}
	
	
	public void actionPerformed(ActionEvent e) {
		/* ====================================================== */
		if (CMD_ADD_MEMO.equals(e.getActionCommand())) {
			addMemo();
		}
		if (CMD_REMOVE_MEMO.equals(e.getActionCommand())) {
			deleteMemo((MemoItem) lastClickedItem);
		}
		if (CMD_CLOSE.equals(e.getActionCommand())) {
			this.showDialog(false);
		}
		/* ====================================================== */
	}
	
	

	public void mouseClicked(MouseEvent e) {}
	public void mouseEntered(MouseEvent e) {}
	public void mouseExited(MouseEvent e) {}
	
	public void mousePressed(MouseEvent e) {
		/* ====================================================== */
		this.lastClickedItem = (MemoItem) e.getSource();
		showPopup(e);
		/* ====================================================== */
	}
	public void mouseReleased(MouseEvent e) {
		/* ================================================== */
		this.lastClickedItem = (MemoItem) e.getSource();
		showPopup(e);
		/* ================================================== */
	}
	
	/**
	 * @param e
	 */
	private void showPopup(MouseEvent e) {
		/* ================================================== */
		if (e.isPopupTrigger()) {
			/* ------------------------------------------------------- */
			this.lastClickedItem = (MemoItem) e.getSource();
			this.popup.show(e.getComponent(), e.getX(), e.getY());
			/* ------------------------------------------------------- */
		}
		/* ================================================== */
	}
	
	/**
	 * @author martin.heinemann@tudor.lu
	 * 03.10.2007
	 * 16:51:45
	 *
	 *
	 * @version
	 * <br>$Log: SimpleMemoView.java,v $
	 * <br>Revision 1.3  2010-10-19 14:37:15  troth
	 * <br>rename class SimpleViewPanel in OverviewPanel
	 * <br>
	 * <br>Revision 1.2  2010-03-24 18:46:56  troth
	 * <br>Redesign of the patient view history - SimpleMemoView extends now from GECAMedBaseDialog
	 * <br>
	 * <br>Revision 1.1  2010-03-23 15:17:19  troth
	 * <br>Redesign of the patient view history
	 * <br>
	 * <br>Revision 1.4  2008-09-25 09:43:06  heinemann
	 * <br>fixed copyrights
	 * <br>
	 * <br>Revision 1.3  2008-01-21 14:58:42  heinemann
	 * <br>code cleanup and java doc
	 * <br>
	 * <br>Revision 1.2  2007-10-22 09:58:14  heinemann
	 * <br>*** empty log message ***
	 * <br>
	 * <br>Revision 1.1  2007-10-16 08:23:26  heinemann
	 * <br>*** empty log message ***
	 * <br>
	 *   
	 */
	class MemoItem extends JPanel {

		/**
		 * 
		 */
		private static final long serialVersionUID = 1L;
		
		
		
		
		private PatientMemo memo;
		private JLabel centerLabel;
		private JLabel iconLabel;
		private JLabel authorLabel;
		
		/**
		 * 
		 */
		public MemoItem() {
			/* ================================================== */
			this(null);
			/* ================================================== */
		}
		
		/**
		 * @param memo
		 */
		public MemoItem(PatientMemo memo) {
			/* ================================================== */
			this.setLayout(new BorderLayout(5, 5));
			this.setBackground(Color.WHITE);
			
			/* ------------------------------------------------------- */
			// left column -> icon
			this.iconLabel = new JLabel();
			iconLabel.setVerticalAlignment(JLabel.TOP);
			/* ------------------------------------------------------- */
			// center -> text
			this.centerLabel = new JLabel();
			centerLabel.setFont(new Font("Arial", Font.PLAIN, 12));
			
			/* ------------------------------------------------------- */
			// bottom -> author
			this.authorLabel = new JLabel();
			authorLabel.setHorizontalTextPosition(JLabel.RIGHT);
			authorLabel.setHorizontalAlignment(SwingConstants.RIGHT);
			/* ------------------------------------------------------- */
			this.add(iconLabel,   BorderLayout.WEST);
			this.add(centerLabel, BorderLayout.CENTER);
			this.add(authorLabel, BorderLayout.SOUTH);
			this.add(new JLabel(" "), BorderLayout.EAST);
			setMemo(memo);
			/* ------------------------------------------------------- */
			this.addMouseListener(new MouseAdapter() {

				/* (non-Javadoc)
				 * @see java.awt.event.MouseAdapter#mouseClicked(java.awt.event.MouseEvent)
				 */
				@Override
				public void mouseClicked(MouseEvent e) {
					/* ====================================================== */
						MemoItem.this.requestFocus();
						if (e.getClickCount() == 2) {
							/* ------------------------------------------------------- */
							boolean wasImportant = MemoItem.this.memo.getImportant();
							PatientMemoDialog dialog = new PatientMemoDialog();
							
							dialog.showMemoDialog(MemoItem.this.memo);
							memoControler.saveMemo(dialog.getMemo(), wasImportant);
							/* ------------------------------------------------------- */
						}
//					}
					/* ====================================================== */
				}
			});
			
			this.addFocusListener(new FocusAdapter() {
				
				@Override
				public void focusGained(FocusEvent e) {
					/* ====================================================== */
					MemoItem.this.setBackground(OverviewPanel.LIGHT_BACK);
					/* ====================================================== */
				}

				@Override
				public void focusLost(FocusEvent e) {
					/* ====================================================== */
					MemoItem.this.setBackground(Color.WHITE);
					/* ====================================================== */
				}
			});
			
			/* ================================================== */
		}
		
		
		/**
		 * @param memo
		 */
		public void setMemo(PatientMemo memo) {
			/* ================================================== */
			this.memo = memo;
			if (memo == null) {
				iconLabel.setEnabled(false);
				centerLabel.setText("");
				authorLabel.setText("");
			} else {
				/* ------------------------------------------------------- */
				if (memo.getImportant() == true)
					iconLabel.setIcon(PatientManagerModule.getIcon(PatientManagerModule.WARNING));
				else
					iconLabel.setIcon(PatientManagerModule.getIcon(PatientManagerModule.LINK_SPACE));
				centerLabel.setText((memo.getNote() != null ? memo.getNote() : ""));
				
				if (memo.getAuthor() != null) {
					/* ------------------------------------------------------- */
					StringBuffer buff = new StringBuffer();
					
					buff.append((memo.getAuthor() != null ? memo.getAuthor() : ""));
					buff.append((memo.getCreationDate() != null ? " - "+formater.format(memo.getCreationDate()) : ""));
					authorLabel.setText("<html><p align=\"right\"><b>"+buff.toString()+"</b>&nbsp;</html>");
					/* ------------------------------------------------------- */
				} else
					authorLabel.setText("");
				/* ------------------------------------------------------- */
			}
			/* ================================================== */
		}
		
		public PatientMemo getMemo() {
			/* ================================================== */
			return this.memo;
			/* ================================================== */
		}
		
		
	}

	public void propertyChange(PropertyChangeEvent evt) {
		/* ====================================================== */
		setMemos(memoControler.getMemos());
		/* ====================================================== */
	}
}
