/*******************************************************************************
 * 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.patient.gui.allergy;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JButton;
import javax.swing.JEditorPane;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import lu.tudor.santec.gecamed.core.gui.GECAMedIconNames;
import lu.tudor.santec.gecamed.core.gui.GECAMedLists;
import lu.tudor.santec.gecamed.core.gui.GECAMedModule;
import lu.tudor.santec.gecamed.core.gui.utils.GECAMedTitledBorder;
import lu.tudor.santec.gecamed.core.gui.utils.MultiLineCellEditor;
import lu.tudor.santec.gecamed.core.gui.utils.MultiLineCellRenderer;
import lu.tudor.santec.gecamed.patient.ejb.entity.beans.Allergens;
import lu.tudor.santec.i18n.Translatrix;

import org.apache.log4j.Logger;

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

/**
 * JPanel to add/edit the patients allergies
 * the panel contains a list of all existing allergies on the left, and 
 * a table with the patients allergies on the right.
 *
 * @author Johannes Hermen johannes.hermen(at)tudor.lu
 *
 * @version
 * <br>$Log: AllergyPanel.java,v $
 * <br>Revision 1.11  2013-12-27 18:09:10  donak
 * <br>Cleanup of imports
 * <br>
 * <br>Revision 1.10  2013-07-15 06:18:35  ferring
 * <br>logging changed
 * <br>
 * <br>Revision 1.9  2013-02-19 12:07:34  ferring
 * <br>GECAMedLists changed. Will now automatically load list of all beans
 * <br>
 * <br>Revision 1.8  2008-09-25 09:43:08  heinemann
 * <br>fixed copyrights
 * <br>
 * <br>Revision 1.7  2008-01-21 14:08:58  hermen
 * <br>*** empty log message ***
 * <br>
 *
 */
public class AllergyPanel extends JPanel implements ActionListener {

	private static final long serialVersionUID = 1L;
	private JTextField searchField;
	private JList searchList;
	private JTable allergyTable;
	private JButton removeButton;
	private JButton addButton;
//	private HistoryManager manager;
	private Allergens[] all;
	private JEditorPane infoLabel;
	private AllergyTableModel model;
	private JButton newButton;

	private static Logger m_Logger = Logger.getLogger ("lu.tudor.santec.gecamed.patient.gui.history.antecedents");


	public AllergyPanel(AllergyTableModel allergyTableModel) {
		this.model = allergyTableModel;

		this.setOpaque(false);

		this.setBorder(new GECAMedTitledBorder(Translatrix.getTranslationString("patient.allergy.allergies")));

		this.setLayout(new FormLayout(
				"3dlu, fill:135dlu, 10dlu, fill:pref, 10dlu, left:230dlu, 3dlu", // cols
				"3dlu, pref, 3dlu, pref, 5dlu, fill:140dlu:grow, 3dlu, fill:90dlu, 3dlu")); // rows
		CellConstraints cc = new CellConstraints();

 		try {
 			all = GECAMedLists.getArray(Allergens.class);
// 			manager = (HistoryManager) ManagerFactory.getRemote(HistoryManagerBean.class);
// 			if (all == null) {
// 				List<Allergens> l = new ArrayList<Allergens>(manager.getAllergens());
// 				Collections.sort(l, new Comparator() {
//					public int compare(Object o1, Object o2) {
//						return o1.toString().toLowerCase().compareTo(o2.toString().toLowerCase());
//					}
// 				});
// 				all = l.toArray(new Allergens[0]);
// 				GECAMedLists.storeList(Allergens.class, all);
// 			}

 			}
 		catch (Exception p_Exception)
 			{
 			m_Logger.warn(p_Exception.getLocalizedMessage());
 			}



		this.searchField = new JTextField();
		this.searchField.addKeyListener(new KeyAdapter() {
			@Override
			public void keyTyped(KeyEvent e) {
				for (int i = 0; i < all.length; i++) {
					if (all[i].toString().toLowerCase().startsWith(searchField.getText().toLowerCase())) {
						searchList.setSelectedValue(all[i], true);
						break;
					}
				}
				searchList.setSelectedIndex(-1);
			}
		});


		this.searchList = new JList(all);

		this.searchList.addListSelectionListener(new ListSelectionListener() {
			public void valueChanged(ListSelectionEvent e) {
				infoLabel.setText(((Allergens)searchList.getSelectedValue()).toInfoString());
				infoLabel.setCaretPosition(0);
			}
		});

		this.searchList.addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent e) {
				if (e.getClickCount() >= 2) {
					model.addAllergen((Allergens)searchList.getSelectedValue());
				}
			}
		});

		this.addButton = new JButton(GECAMedModule.getMediumIcon(GECAMedIconNames.RIGHT));
		addButton.setMargin(new java.awt.Insets(0, 2, 0, 2));
		addButton.addActionListener(this);
		addButton.setToolTipText(Translatrix.getTranslationString("patient.allergy.addAllergyFromList"));

		this.newButton = new JButton(GECAMedModule.getMediumIcon(GECAMedIconNames.ADD_LINE));
		newButton.setMargin(new java.awt.Insets(0, 2, 0, 2));
		newButton.addActionListener(this);
		newButton.setToolTipText(Translatrix.getTranslationString("patient.allergy.addAllergyNew"));

		this.removeButton = new JButton(GECAMedModule.getMediumIcon(GECAMedIconNames.LEFT));
		removeButton.setMargin(new java.awt.Insets( 0, 2, 0, 2));
		removeButton.addActionListener(this);
		removeButton.setToolTipText(Translatrix.getTranslationString("patient.allergy.removeAllergy"));

		this.allergyTable = new JTable(model);

		allergyTable.getColumnModel().getColumn(1).setCellEditor(new MultiLineCellEditor());
		allergyTable.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);

		MultiLineCellRenderer mr = new MultiLineCellRenderer();

		allergyTable.setSurrendersFocusOnKeystroke(true);

		allergyTable.getColumnModel().getColumn(0).setCellRenderer(mr);
		allergyTable.getColumnModel().getColumn(1).setCellRenderer(mr);

		this.infoLabel = new JEditorPane();
		this.infoLabel.setContentType("text/html");
		this.infoLabel.setEditable(false);

		this.add(new JLabel(Translatrix.getTranslationString("patient.allergy.search") + ":"), cc.xy(2,2));
		this.add(searchField, cc.xy(2,4));
		JScrollPane jsp1 = new JScrollPane(searchList);
		jsp1.setOpaque(false);
		jsp1.getViewport().setOpaque(false);
		this.add(jsp1, cc.xy(2,6));

		JPanel buttonPanel = new JPanel(new FormLayout("pref", "pref:grow, pref, pref:grow, pref, pref:grow, pref, pref:grow"));
		buttonPanel.add(addButton, cc.xy(1,2));
		buttonPanel.add(newButton, cc.xy(1,4));
		buttonPanel.add(removeButton, cc.xy(1,6));
		buttonPanel.setOpaque(false);
		this.add(buttonPanel, cc.xy(4,6));


		this.add(new JLabel(Translatrix.getTranslationString("patient.allergy.allergies") + ":"), cc.xy(6,2));
		JScrollPane jsp2 = new JScrollPane(allergyTable);
		jsp2.setOpaque(false);
		jsp2.getViewport().setOpaque(false);
		this.add(jsp2, cc.xy(6,6));

		JScrollPane jsp3 = new JScrollPane(infoLabel);
		jsp3.setOpaque(false);
		jsp3.getViewport().setOpaque(false);
		this.add(jsp3, cc.xyw(2,8,5));

	}

	/* (non-Javadoc)
	 * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
	 */
	public void actionPerformed(ActionEvent e) {
		if (e.getSource().equals(this.addButton)) {
			model.addAllergen((Allergens)searchList.getSelectedValue());
		} else if (e.getSource().equals(this.removeButton)) {
			model.deleteAllergen(allergyTable.getSelectedRow());
		} else if (e.getSource().equals(this.newButton)) {
			Allergens al = new Allergens();
			al.setId(-1);
			model.addAllergen(al);
			/* ------------------------------------------------------- */
			int row = model.getRowCount()-1;
			int col = 0;
			model.setValueAt("", row, col);
			allergyTable.requestFocus();
			allergyTable.editCellAt(row, col, e);
		}
	}
	
	public void stopEditing() {
		try {
			if (allergyTable.isEditing()) {
				allergyTable.getCellEditor().stopCellEditing();							
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
