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

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.Icon;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.ScrollPaneConstants;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.event.CellEditorListener;
import javax.swing.event.ChangeEvent;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.undo.UndoManager;

import lu.tudor.santec.gecamed.core.gui.GECAMedAction;
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.PrescriptionType;
import lu.tudor.santec.gecamed.prescription.gui.PrescriptionIcons;
import lu.tudor.santec.i18n.Translatrix;

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

/**
 * Component for the input field for non drug prescriptions and drug prescriptions.
 * According to a given prescription type
 * it will return  a JTextArea or a JTable
 *
 *
 * @author martin.heinemann@tudor.lu
 *
 *
 * @version
 * <br>$Log: DrugInputComponent.java,v $
 * <br>Revision 1.11  2010-10-11 08:11:48  troth
 * <br>remove TODO
 * <br>
 * <br>Revision 1.10  2010-03-30 10:41:37  troth
 * <br>Redesign of the prescription view - change icon manager class
 * <br>
 * <br>Revision 1.9  2008-10-21 12:28:27  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.8  2008-10-14 12:18:28  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.7  2008-10-13 09:26:47  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.6  2008-09-25 09:43:08  heinemann
 * <br>fixed copyrights
 * <br>
 * <br>Revision 1.5  2008-01-15 13:40:46  heinemann
 * <br>better documentation
 * <br>
 * <br>Revision 1.4  2007/07/04 08:50:50  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.3  2007/03/30 12:18:00  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.2  2007/03/02 08:28:42  hermen
 * <br>initial checkin after the merge of PatientModuleRebuild with the main HEAD
 * <br>
 * <br>Revision 1.1.2.9  2007/02/21 10:00:40  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.1.2.8  2007/01/11 08:50:26  heinemann
 * <br>Complete - # 34: DrugInputComponent -> wrapstyle word
 * <br>http://santec.tudor.lu:8888/gecamed/ticket/34
 * <br>
 * <br>Revision 1.1.2.7  2007/01/08 09:51:59  heinemann
 * <br>Incomplete - # 21: Context Menu -> create new prescription
 * <br>http://santec.tudor.lu:8888/gecamed/ticket/21
 * <br>
 * <br>Revision 1.1.2.6  2007/01/05 13:26:13  heinemann
 * <br>improved the cell editor.
 * <br>It now resizes in case the linecount is larger than the textarea
 * <br>
 * <br>Revision 1.1.2.5  2007/01/05 10:37:42  heinemann
 * <br>complete - # 23: Anamnesis/Drug Table editorComponent needs focus
 * <br>http://santec.tudor.lu:8888/gecamed/ticket/23
 * <br>
 * <br>fixed:
 * <br>
 * <br>table.setSurrendersFocusOnKeystroke(true)
 * <br>
 * <br>Revision 1.1.2.4  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.3  2006/12/28 10:32:26  heinemann
 * <br>bug fixing and template improvements
 * <br>
 * <br>Revision 1.1.2.2  2006/12/21 15:56:06  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.1.2.1  2006/12/21 14:26:43  heinemann
 * <br>*** empty log message ***
 * <br>
 */
public class DrugInputComponent implements MouseListener {

	private JPanel textPanel;
	private UndoTextArea textTextArea;
	private EditorDrugTableModel model;
	private JPanel drugPanel;
	private JTable drugTable;
	private JPopupMenu popup;
	private GECAMedAction clearAction;
	private JComponent currentComponent;
	private DrugCellEditor drugCellEditor;
	private DrugCellRenderer drugCellRenderer;
	private GECAMedAction removeCurrentDrugAction;



	/**
	 * @param model
	 */
	public DrugInputComponent(EditorDrugTableModel model) {
		/* ====================================================== */
		this.model = model;
		createInputPanel();
		createDrugPanel();

		initMouseListener();
		/* ====================================================== */
	}


	/**
	 * Init the mouselistener for the context menu
	 */
	private void initMouseListener() {
		/* ============================================= */

		this.popup = new JPopupMenu();

		// the clear item
		this.clearAction = new GECAMedAction(null,
				"prescription.buttons.clear",
				PrescriptionIcons.getMiniIcon(PrescriptionIcons.DELETE),
				null, // ?
				false, false, false) {

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

					/* (non-Javadoc)
					 * @see lu.tudor.santec.gecamed.core.gui.GECAMedAction#actionPerformed(java.awt.event.ActionEvent)
					 */
					@Override
					public void actionPerformed(ActionEvent p_Event) {
						/* ============================================= */
						if (currentComponent.equals(drugPanel)) {
							model.reset();
						}
						else
							textTextArea.setText("");
						/* ============================================= */
					}
		};
		/* ------------------------------------------------------- */
		// the remove the current drug action
		/* ------------------------------------------------------- */
		this.removeCurrentDrugAction = new GECAMedAction(null,
				"prescription.buttons.removeDrug",
				PrescriptionIcons.getMiniIcon(PrescriptionIcons.DELETE_DRUG),
				null, // ?
				false, false, false) {

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

					/* (non-Javadoc)
					 * @see lu.tudor.santec.gecamed.core.gui.GECAMedAction#actionPerformed(java.awt.event.ActionEvent)
					 */
					@Override
					public void actionPerformed(ActionEvent p_Event) {
						/* ============================================= */
						if (currentComponent.equals(drugPanel)) {
							/* ------------------------------------------------------- */
							// delete the current drug
							/* ------------------------------------------------------- */
							int selectedRow = drugTable.getSelectedRow();
							model.deleteDrug(selectedRow);
							/* ------------------------------------------------------- */
						}
						else
							textTextArea.setText("");
						/* ============================================= */
					}
		};
		popup.add(this.removeCurrentDrugAction);
		
		popup.add(clearAction);


		drugTable.addMouseListener(this);

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


	/**
	 * Create the input panel
	 */
	private void createInputPanel() {
		/* ============================================= */
		// first, create the text panel
		this.textPanel = new JPanel(new BorderLayout());
		this.textTextArea = new UndoTextArea(new UndoManager());
		// add items to the menu of the textTextArea
		this.textTextArea.getPopupMenu().add(clearAction);
		this.textTextArea.setLineWrap(true);
		this.textTextArea.setWrapStyleWord(true);
//		this.textTextArea.getDocument().addDocumentListener(this);
		/* ------------------------------------------------------ */
		JScrollPane tScroll = new JScrollPane(textTextArea);
		tScroll.setVerticalScrollBarPolicy(
				ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
		/* ------------------------------------------------------ */
		textPanel.add(tScroll);
		/* ------------------------------------------------------ */
		/* ============================================= */
	}


	/**
	 * Create the drug panel
	 */
	private void createDrugPanel() {
		/* ====================================================== */
		this.drugPanel = new JPanel(new BorderLayout());
		this.drugPanel = new JPanel(new FormLayout("fill:10dlu:grow", "fill:10dlu:grow"));

		this.drugTable = new JTable();

		/* ------------------------------------------------------ */
		JScrollPane dScroll = new JScrollPane(drugTable);
		dScroll.setVerticalScrollBarPolicy(
				ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
		dScroll.getViewport().setBackground(GECAMedColors.c_ScrollPaneBackground);
		dScroll.setAutoscrolls(true);
		/* ------------------------------------------------------ */

		this.drugCellEditor 	= new DrugCellEditor();
		this.drugCellRenderer 	= new DrugCellRenderer();
		/* ------------------------------------------------------- */
		drugTable.setModel(this.model);
		drugTable.setTableHeader(null);
		drugTable.getColumnModel().getColumn(0).setCellRenderer(this.drugCellRenderer);
		drugTable.getColumnModel().getColumn(0).setCellEditor(this.drugCellEditor);
		drugTable.getColumnModel().getColumn(1).setMaxWidth(32);
		drugTable.getColumnModel().getColumn(1).setMinWidth(32);

		drugTable.getColumnModel().getColumn(1).setCellRenderer(new ImageCellRenderer());

		drugTable.setSurrendersFocusOnKeystroke(true);
		/* ------------------------------------------------------- */
		// listeners for the drug cell editor
		// after editing a drug, the cursor should jump to the
		// posology line
		/* ------------------------------------------------------- */
		
		this.drugCellEditor.addCellEditorListener(new CellEditorListener() {

			public void editingCanceled(ChangeEvent e) {}

			public void editingStopped(ChangeEvent e) {
				/* ====================================================== */
				// send focus to the next line
				/* ------------------------------------------------------- */
				if (drugCellEditor.hasFocus()) {
					int editRow = drugCellEditor.getRowIndex();
					drugTable.requestFocusInWindow();
					drugTable.editCellAt(editRow + 1, 0);
				}
				
				/* ====================================================== */
			}
			
		});
		/* ------------------------------------------------------- */
		CellConstraints cc = new CellConstraints();
		/* ------------------------------------------------------ */
		drugPanel.add(dScroll, cc.xy(1, 1));
		/* ====================================================== */
	}


	/**
	 * Returns the textArea
	 *
	 * @return
	 */
	public JTextArea getTextArea() {
		/* ====================================================== */
		return this.textTextArea;
		/* ====================================================== */
	}


	/**
	 * Returns the panel for a type
	 *
	 * @param type
	 * @return
	 */
	public JPanel getPanel(String type) {
		/* ====================================================== */
		if (PrescriptionType.MEDICINE.equals(type)) {
			this.currentComponent = drugPanel;
			return this.drugPanel;
		}
		else {
			this.currentComponent = textPanel;
			return this.textPanel;
		}
		/* ====================================================== */
	}


	/**
	 * @return
	 */
	public JTable getTable() {
		/* ============================================= */
		return this.drugTable;
		/* ============================================= */
	}


	public void setEnable(boolean b) {
		/* ============================================= */
		this.drugTable.setEnabled(b);
		this.textTextArea.setEnabled(b);
		this.currentComponent.setEnabled(b);
		/* ============================================= */
	}


	public void mouseClicked(MouseEvent e) {}
	public void mouseEntered(MouseEvent e) {}
	public void mouseExited(MouseEvent e) {}
		
	public void mousePressed(MouseEvent e) {
		/* ============================================= */
		if (SwingUtilities.isRightMouseButton(e)) {
			int row = this.drugTable.rowAtPoint(e.getPoint());
			if (row > -1)
				drugTable.getSelectionModel().setSelectionInterval(row, row);
		}
		showPopup(e);
		/* ============================================= */
	}


	public void mouseReleased(MouseEvent e) {
		/* ============================================= */
		showPopup(e);
		/* ============================================= */
	}


	/**
	 * Show the popup
	 *
	 * @param e
	 */
	private void showPopup(MouseEvent e) {
		/* ====================================================== */
		if (e.isPopupTrigger()) {
			/* ------------------------------------------------------ */
			// enable/disable actions
			clearAction.setEnabled(currentComponent.isEnabled());
//			clearAction.setEnabled(false);

			popup.show(currentComponent, e.getX(), e.getY());
		}
		/* ====================================================== */
	}


	/* *************************************************************+
	 * Inner class
	 *
	 * The cell renderer for the icon-buttons
	 */

	/**
	 * @author martin.heinemann@tudor.lu
	 * 15.01.2008
	 * 13:19:54
	 *
	 *
	 * @version
	 * <br>$Log: DrugInputComponent.java,v $
	 * <br>Revision 1.11  2010-10-11 08:11:48  troth
	 * <br>remove TODO
	 * <br>
	 * <br>Revision 1.10  2010-03-30 10:41:37  troth
	 * <br>Redesign of the prescription view - change icon manager class
	 * <br>
	 * <br>Revision 1.9  2008-10-21 12:28:27  heinemann
	 * <br>*** empty log message ***
	 * <br>
	 * <br>Revision 1.8  2008-10-14 12:18:28  heinemann
	 * <br>*** empty log message ***
	 * <br>
	 * <br>Revision 1.7  2008-10-13 09:26:47  heinemann
	 * <br>*** empty log message ***
	 * <br>
	 * <br>Revision 1.6  2008-09-25 09:43:08  heinemann
	 * <br>fixed copyrights
	 * <br>
	 * <br>Revision 1.5  2008-01-15 13:40:46  heinemann
	 * <br>better documentation
	 * <br>
	 *   
	 */
	class ImageCellRenderer extends  DefaultTableCellRenderer{

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

		private Icon cefip = PrescriptionIcons.getMiniIcon(PrescriptionIcons.SUBSTANCE);
		private Icon poso = PrescriptionIcons.getMiniIcon(PrescriptionIcons.DRUG_INFO);

		private JLabel cLabel;
		private JLabel pLabel;


		public ImageCellRenderer() {
			/* ================================================== */
			this.setHorizontalAlignment(JLabel.CENTER);
			cLabel = new JLabel();
			cLabel.setIcon(cefip);
			cLabel.setToolTipText(Translatrix.getTranslationString("prescription.tooltip.openCefipBrowser"));


			pLabel = new JLabel();
			pLabel.setIcon(poso);
			pLabel.setToolTipText(Translatrix.getTranslationString("prescription.tooltip.openPosologyChooser"));

			pLabel.setVerticalAlignment(SwingConstants.TOP);
			cLabel.setVerticalAlignment(SwingConstants.TOP);

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

		public Component getTableCellRendererComponent(JTable table, Object value,
				boolean isSelected, boolean hasFocus, int row, int column) {
			/* ================================================== */
			if (row % 2 == 0)
				return cLabel;
			else
				return pLabel;
			/* ================================================== */
		}



	}




}
