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

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import java.util.Vector;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.JToggleButton;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

import lu.tudor.santec.gecamed.core.gui.GECAMedColors;
import lu.tudor.santec.gecamed.core.gui.GECAMedLists;
import lu.tudor.santec.gecamed.core.gui.GECAMedModule;
import lu.tudor.santec.gecamed.core.gui.MainFrame;
import lu.tudor.santec.gecamed.core.gui.ModuleManager;
import lu.tudor.santec.gecamed.core.gui.utils.GECAMedGuiUtils;
import lu.tudor.santec.gecamed.core.gui.utils.filtertablemodel.TableFilter;
import lu.tudor.santec.gecamed.esante.gui.tab.ESanteTab;
import lu.tudor.santec.gecamed.formeditor.gui.model.FormHistoryTableModel;
import lu.tudor.santec.gecamed.formeditor.gui.view.FormTab;
import lu.tudor.santec.gecamed.letter.gui.LetterTemplateModule;
import lu.tudor.santec.gecamed.patient.ejb.entity.beans.Incident;
import lu.tudor.santec.gecamed.patient.ejb.entity.beans.IncidentEntryType;
import lu.tudor.santec.gecamed.patient.ejb.entity.beans.Patient;
import lu.tudor.santec.gecamed.patient.ejb.session.beans.IncidentManagerBean;
import lu.tudor.santec.gecamed.patient.ejb.session.interfaces.IncidentManager;
import lu.tudor.santec.gecamed.patient.gui.PatientManagerIconNames;
import lu.tudor.santec.gecamed.patient.gui.PatientManagerModule;
import lu.tudor.santec.gecamed.patient.gui.PatientPanel;
import lu.tudor.santec.gecamed.patient.gui.PatientViewTab;
import lu.tudor.santec.gecamed.patient.gui.history.HistoryDataAgent;
import lu.tudor.santec.gecamed.patient.gui.history.table.HistoryTablePanel;
import lu.tudor.santec.gecamed.patient.gui.history.table.filter.HistoryDateFilter;
import lu.tudor.santec.gecamed.patient.gui.history.table.filter.HistoryFulltextFilter;
import lu.tudor.santec.gecamed.patient.gui.history.table.filter.HistoryTypeFilter;
import lu.tudor.santec.gecamed.patient.gui.settings.ConsultationEntryConfig;
import lu.tudor.santec.gecamed.patient.gui.settings.HistoryTabEntryConfig;
import lu.tudor.santec.gecamed.patient.gui.settings.PatientModuleSettings;
import lu.tudor.santec.i18n.Translatrix;
import lu.tudor.santec.settings.SettingEvent;
import lu.tudor.santec.settings.SettingListener;
import lu.tudor.santec.settings.SettingsPlugin;
import lu.tudor.santec.widgets.gui.ButtonFactory;

import org.apache.log4j.Logger;
import org.apache.xmlbeans.impl.tool.TypeHierarchyPrinter;

import bizcal.util.DateUtil;

import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;
import com.toedter.calendar.JDateChooser;
import com.toedter.calendar.JTextFieldDateEditor;

/**
 * @author martin.heinemann@tudor.lu 24.06.2008 15:41:22
 *
 *
 * @version <br>
 *          $Log: HistoryViewTab.java,v $ <br>
 *          Revision 1.23 2013-10-11 14:59:09 ferring <br>
 *          *** empty log message *** <br>
 *          <br>
 *          Revision 1.22 2013-02-19 12:07:34 ferring <br>
 *          GECAMedLists changed. Will now automatically load list of all beans
 *          <br>
 *          <br>
 *          Revision 1.21 2012-03-13 12:11:22 ferring <br>
 *          Form types are now separated by the code column in of the table
 *          incident_entry <br>
 *          <br>
 *          Revision 1.20 2011-11-28 14:10:17 ferring <br>
 *          FormEditor added, but not shown in module manager plugin <br>
 *          <br>
 *          Revision 1.19 2010-11-23 08:42:42 ferring <br>
 *          the last update was using a java 1.6 method. Changed to the java 1.5
 *          compatible method. <br>
 *          <br>
 *          Revision 1.18 2010-11-22 15:09:20 ferring <br>
 *          FormEditor kicked <br>
 *          <br>
 *          Revision 1.17 2010-11-22 15:08:23 ferring <br>
 *          bug in history search fixed. <br>
 *          FromDate field was ignored, if set to null, after it was set once.
 *          <br>
 *          In Addition the form history was redesigned, so that fixes in the
 *          HistoryViewTab will have affect to the FormHistoryView. <br>
 *          <br>
 *          Revision 1.16 2010-10-07 12:50:43 troth <br>
 *          Complete - # 617: Can't search for prescription text in history view
 *          <br>
 *          http://santec.tudor.lu/trac/gecamed/ticket/617 <br>
 *          <br>
 *          Revision 1.15 2010-09-23 12:20:58 hermen <br>
 *          *** empty log message *** <br>
 *          <br>
 *          Revision 1.14 2010-08-24 14:08:35 troth <br>
 *          set new color for open prescription in prescription history <br>
 *          <br>
 *          Revision 1.13 2010-08-24 12:48:31 troth <br>
 *          formeditor include test <br>
 *          <br>
 *          Revision 1.12 2010-06-09 06:41:39 hermen <br>
 *          *** empty log message *** <br>
 *          <br>
 *          Revision 1.11 2010-05-18 13:01:20 ferring <br>
 *          reference on a static variable changed, because the variable moved
 *          into another class <br>
 *          <br>
 *          Revision 1.10 2010-05-05 11:24:10 ferring <br>
 *          form history tab added <br>
 *          <br>
 *          Revision 1.9 2010-04-26 16:39:03 troth <br>
 *          Redesign of the prescription view <br>
 *          <br>
 *          Revision 1.8 2010-03-23 15:15:13 troth <br>
 *          Redesign of the patient view history - <br>
 *          add tabs for files and prescriptions <br>
 *          <br>
 *          Revision 1.7 2008-12-05 17:34:23 heinemann <br>
 *          moved some basic classes to lu.tudor.santec.widgets <br>
 *          <br>
 *          Revision 1.6 2008-09-25 09:43:10 heinemann <br>
 *          fixed copyrights <br>
 *          <br>
 *          Revision 1.5 2008-09-24 11:54:08 heinemann <br>
 *          added first run actions to gecamed. will disable all views except
 *          the ones of the admin tab for user, office and physician. <br>
 *          Tabs are enabled, if an physican was saved. <br>
 *          <br>
 *          Revision 1.4 2008-07-23 09:44:53 heinemann <br>
 *          *** empty log message *** <br>
 *          <br>
 *          Revision 1.3 2008-07-15 12:16:33 heinemann <br>
 *          *** empty log message *** <br>
 *          <br>
 *          Revision 1.2 2008-07-04 13:38:17 heinemann <br>
 *          Complete - task 5: Create Icon for History List Views <br>
 *          <br>
 *          Revision 1.1 2008-07-03 11:59:57 heinemann <br>
 *          *** empty log message *** <br>
 * 
 */
public class HistoryViewTab extends PatientViewTab implements ActionListener, PropertyChangeListener, DocumentListener {

	/**
	 * static logger for this class
	 */
	private static Logger logger = Logger.getLogger(HistoryViewTab.class.getName());

	private static final long serialVersionUID = 1L;

	public static final String NAME = "HISTORY_VIEW";

	protected PatientPanel patientPanel;

	protected HistoryTablePanel historyTablePanel;

	protected JPanel searchPanel;

	protected JButton clearButton;

	protected JTextField textField;

	protected JDateChooser fromDateChooser;

	protected JComboBox typeBox;

	protected HistoryTypeFilter typeFilter;

	protected HistoryFulltextFilter textFilter;

	// private HistoryTableModel model;

	protected JDateChooser toDateChooser;

	protected HistoryDateFilter dateFilter;

	protected JTabbedPane historyTab;


	private Vector<HistoryTablePanel> panels = new Vector<HistoryTablePanel>();

	protected HistoryTablePanel formTablePanel;

	private JButton reload;

	public static HistoryTabEntryConfig fullview = null;
	public static HistoryTabEntryConfig diagnosis = null;
	public static HistoryTabEntryConfig letters = null;
	public static HistoryTabEntryConfig files = null;
	public static HistoryTabEntryConfig prescriptions = null;
	public static HistoryTabEntryConfig forms = null;
	public static HistoryTabEntryConfig cda = null;

	Collection<IncidentEntryType> entryTypes;
	private Vector<HistoryTabEntryConfig> historytabEntries = new Vector<HistoryTabEntryConfig>();
	private Vector<JToggleButton> buttonsList;

	private Vector<HistoryTypeFilter> filterList;

	private String typetoShow = null;
	private boolean showTypeFilter = true;
	private boolean refresh=false;
	private JPanel buttonsPanel;
	
	
	/**
	 * @param panel
	 */
	public HistoryViewTab(PatientPanel panel) {
		this(panel, true, null);
	}

	public HistoryViewTab(PatientPanel panel, boolean showTypeFilter, String typeFilter) {
		/* ================================================== */

		// Reference to the PatientPanel, to get the history table model

			this.patientPanel = panel;
			// Setting the Icon of the PatientViewTab
			this.setIcon(PatientManagerModule.getMediumIcon(PatientManagerIconNames.HISTORY_LISTS));
			this.setTitle(Translatrix.getTranslationString("patient.history_lists"));
	
			this.showTypeFilter = showTypeFilter;
			typetoShow = typeFilter;
		
		initComponent();

	}

	/**
	 * 
	 */
	private void initComponent() {
		/* ================================================== */
		// Content
		entryTypes = IncidentManagerBean.getInstance().getAllEntryTypes();

		// Accidents Entry Type
		IncidentEntryType et = new IncidentEntryType();
		et.setName("Ac");
		entryTypes.add(et);

		buttonsList = new Vector<JToggleButton>();
		filterList = new Vector<HistoryTypeFilter>();

		
		JPanel content = new JPanel(new FormLayout("fill:100:grow", "pref,fill:100:grow"));
		content.setOpaque(false);
		CellConstraints cc = new CellConstraints();
		PatientManagerModule patientManagerModule = (PatientManagerModule) ModuleManager
				.getModule(PatientManagerModule.MODULE_NAME);

		/* ------------------------------------------------------- */
		this.setLayout(new BorderLayout());
		this.add(content);

		this.setBackground(GECAMedColors.c_GECAMedBackground);
		/* ------------------------------------------------------- */
		// build search panel
		/* ------------------------------------------------------- */
		this.clearButton = ButtonFactory.createEffectButton(GECAMedModule.getMediumIcon(GECAMedModule.EDIT_CLEAR_LTR));
		this.textField = new JTextField();
		this.fromDateChooser = GECAMedGuiUtils.getDateChooser(false);
		this.toDateChooser = GECAMedGuiUtils.getDateChooser(false);
		this.typeBox = new JComboBox();
		
		this.reload = ButtonFactory.createEffectButton(GECAMedModule.getMediumIcon(GECAMedModule.RELOAD));
		this.reload.setToolTipText(Translatrix.getTranslationString("core.reload"));

		this.searchPanel = new JPanel();
		FormLayout f;
		if (showTypeFilter) {
			f = new FormLayout(// cols
					"1dlu," + "fill:pref," + // suchicon
							"5dlu," + "fill:pref," + // tilesuche
							"3dlu," + "40dlu:grow," + // suchfeld
							"5dlu," + "fill:pref," + // von
							"3dlu," + "fill:60dlu," + // textfeld
							"3dlu," + "fill:pref," + // bis
							"3dlu," + "fill:60dlu," + // textfeld
							"5dlu," + "fill:pref," + // type
							"3dlu," + "fill:pref," + // Textfeld
							"1dlu," + "fill:pref," + // Textfeld
							"1dlu",
					// rows
					"0dlu," + "center:15dlu," + "0dlu," + "20dlu," + "0dlu");
		} else {
			f = new FormLayout(// cols
					"1dlu," + "fill:pref," + // suchicon
							"5dlu," + "fill:pref," + // tilesuche
							"3dlu," + "40dlu:grow," + // suchfeld
							"5dlu," + "fill:pref," + // von
							"3dlu," + "fill:60dlu," + // textfeld
							"3dlu," + "fill:pref," + // bis
							"3dlu," + "fill:60dlu," + // textfeld
							"5dlu," + "fill:pref," + // type
							"3dlu," + "fill:pref," + // Textfeld
							"1dlu," + "fill:pref," + // Textfeld
							"1dlu",
					// rows
					"0dlu," + "center:15dlu," + "0dlu");
		}
		/* ------------------------------------------------------- */
		this.searchPanel.setLayout(f);
		// this.searchPanel.setOpaque(false);
		this.searchPanel.setBackground(GECAMedColors.c_GECAMedBackground);
		/* ------------------------------------------------------- */
		this.searchPanel.add(clearButton, cc.xy(2, 2));

		this.searchPanel.add(new JLabel(Translatrix.getTranslationString("patient.search") + ":"), cc.xy(4, 2));
		this.searchPanel.add(textField, cc.xy(6, 2));
		/* ------------------------------------------------------- */
		this.searchPanel.add(new JLabel(Translatrix.getTranslationString("patient.from") + ":"), cc.xy(8, 2));
		this.searchPanel.add(fromDateChooser, cc.xy(10, 2));
		/* ------------------------------------------------------- */
		this.searchPanel.add(new JLabel(Translatrix.getTranslationString("patient.to") + ":"), cc.xy(12, 2));
		this.searchPanel.add(toDateChooser, cc.xy(14, 2));
		/* ------------------------------------------------------- */
		// this.searchPanel.add(new
		// JLabel(Translatrix.getTranslationString("patient.type")+":"),
		// cc.xy(16, 2));
		// this.searchPanel.add(typeBox, cc.xy(18, 2));
		//
		this.searchPanel.add(reload, cc.xy(16, 2));
		/* ------------------------------------------------------- */

		if (showTypeFilter) {
			// Types buttons

			buttonsPanel = new JPanel();
			GridLayout lay = new GridLayout(1, 18, 3, 0);

			buttonsPanel.setLayout(lay);
			this.searchPanel.add(buttonsPanel, cc.xywh(2, 4, 18, 1));
			
			
			addButtonsToSearchPanel();
		}

		content.add(this.searchPanel, cc.xy(1, 1));
		/* ------------------------------------------------------- */
		// create the history tab to show the different preselected sorts
		/* ------------------------------------------------------- */
		historyTab = new JTabbedPane();

		fetchTypes();

		

		/* ------------------------------------------------------- */
		content.add(this.historyTab, cc.xy(1, 2));
		/* ------------------------------------------------------- */
		initTypeBox();
		initFilter();
		
		initTypeButtons();

		initTabListener();
		
		initListener();

		//Auto Refresh History Tabs when settings have changed
		MainFrame.getInstance().adminSettingsPanel.addSettingListener(new SettingListener() {

			public void settingChanged(SettingEvent arg0) {

				if(buttonsPanel!=null)
				{
					buttonsList.clear();
					try
					{
						buttonsPanel.removeAll();
					}catch(Exception ex)
					{
						ex.printStackTrace();
					}
					
					addButtonsToSearchPanel();
					
					fetchTypes();
					installFilter(textFilter, 3);
					installFilter(dateFilter, 0);
					HistoryDataAgent da = patientPanel.getHistoryDataAgent();
					da.reload();
				}
			}
		});
		
	}

	private void addButtonsToSearchPanel() {
	

			for (IncidentEntryType type : entryTypes) {
				if (!type.getName().equals("")) {

					PatientModuleSettings patientGlobalSettings = PatientManagerModule.getInstance().patientSettings;

					String name = type.getName();
					ConsultationEntryConfig entryConfig = new ConsultationEntryConfig((String) patientGlobalSettings.getValue(name));

					
					if (entryConfig.getId() != null) {
						name = entryConfig.getAcronym();
					//	System.out.println(entryConfig.getName() + "  " + entryConfig.getTranslatedName());
					} else {
						if (name.equals("letter"))
							name = IncidentEntryType.LETTERS;
						else if (name.equals("prescription"))
							name = IncidentEntryType.PRESCRIPTIONS;
						else if (name.equals("file"))
							name = IncidentEntryType.FILES;
						else if (name.equals("form"))
							name = IncidentEntryType.FORM;
						else if (name.equals("dicom"))
							name = IncidentEntryType.DICOM;
						else if (name.equals("labo.result"))
							name = IncidentEntryType.LAB;
						else if (name.equals("cda"))
							name = IncidentEntryType.CDA;

					}

					final JToggleButton button = new JToggleButton(name);
					button.setMargin(new Insets(0, 0, 0, 0));
					button.setActionCommand(type.getName());

//					if (entryConfig.getId() != null) {
//						button.setToolTipText(entryConfig.getTranslatedName() + " ["+type.getName()+"]");				
//					} else {
//						button.setToolTipText(type.getName());
//					}
					if (entryConfig.getId() != null) {
						button.setToolTipText(entryConfig.getTranslatedName() + " ["+type.getName()+"]");				
					} else if (! ("IncidentEntryType." + type.getName()).equals(Translatrix.getTranslationString("IncidentEntryType." + type.getName()))) {
						button.setToolTipText(Translatrix.getTranslationString("IncidentEntryType." + type.getName())+ " ["+type.getName()+"]");
					}else {
						button.setToolTipText(type.getName());
					}
					
					
		      
					buttonsList.addElement(button);
					// button.setPreferredSize(new Dimension(40, 40));
					button.addActionListener(new ActionListener() {

						public void actionPerformed(ActionEvent paramActionEvent) {

							if (button.isSelected()) {


								HistoryTablePanel panel = (HistoryTablePanel) historyTab.getSelectedComponent();
								HistoryTypeFilter filt = filterList.elementAt(historyTab.getSelectedIndex());

								if (filt == null) {
									filt = new HistoryTypeFilter();
								}

								filt.addFilter(button.getActionCommand());

								// panel.getModel().clearFilters();
								panel.getModel().installFilter(filt, 2);
								panel.getModel().setFilteringEnabled(true, 2);

							} else {

								HistoryTablePanel panel = (HistoryTablePanel) historyTab.getSelectedComponent();
								HistoryTypeFilter filt = filterList.elementAt(historyTab.getSelectedIndex());

								if (filt == null) {
									filt = new HistoryTypeFilter();
								}

								filt.removeFilter(button.getActionCommand());

								
								if (filt.size() == 0) {
									enableFilter(false, 2);
								//	enableFilter(false, 3);
									// enableFilter(true, 2);
								}
								else if(filt.size()==1)
								{
									//check if it's a text or a type filter
									String tmp=filt.getElementAt(0);
									if (tmp.charAt(0) == ' ' && tmp.charAt(1) == ' ') {
										//Text filter
										enableFilter(false, 2);
										enableFilter(false, 3);
									}
									else
									{
										//Still one type filter left
										panel.getModel().installFilter(filt, 2);
										panel.getModel().setFilteringEnabled(true, 2);
									}
									
								}

								else {
									// We have more than 1 filter
									panel.getModel().installFilter(filt, 2);
									panel.getModel().setFilteringEnabled(true, 2);
								
								}
								updatePanels();

							}
						}
					});
					buttonsPanel.add(button);
					/*
					 * this.searchPanel.add(button,cc.xy(col+=2, row ));
					 * if(col%20==0) { col=8; row=5; }
					 */
				}

			}

		
		
	}

	@Override
	public String getName() {
		/* ====================================================== */
		return NAME;
		/* ====================================================== */
	}

	/**
	 * Inits the table filters
	 */
	protected void initFilter() {
		/* ================================================== */
		// create the filter
		/* ------------------------------------------------------- */
		this.typeFilter = new HistoryTypeFilter();
		this.textFilter = new HistoryFulltextFilter();
		this.dateFilter = new HistoryDateFilter();


		installFilter(textFilter, 3);
		installFilter(dateFilter, 0);
		// model.installFilter(textFilter, 3);
		// model.installFilter(dateFilter, 0);

	}
 
	/**
	 * 
	 */
	protected void initTypeBox() {
		/* ================================================== */
		typeBox.removeAllItems();
		IncidentEntryType[] types = GECAMedLists.getArray(IncidentEntryType.class);
	
		/* ------------------------------------------------------- */
		if (types == null)
			return;
		/* ------------------------------------------------------- */
		this.typeBox.addItem("");
		Set<String> typeNames = new HashSet<String>();
		for (IncidentEntryType t : types) {
			/* ------------------------------------------------------- */
			if (!typeNames.contains(t.getName())) {
				typeNames.add(t.getName());
				this.typeBox.addItem(t.getName());
			}
			/* ------------------------------------------------------- */
		}
		/* ------------------------------------------------------- */

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

	/**
	 * 
	 */
	protected void initListener() {
		/* ================================================== */
		this.typeBox.addActionListener(this);
		this.fromDateChooser.addPropertyChangeListener(this);
		this.toDateChooser.addPropertyChangeListener(this);

		/* **************************************** */
		/*
		 * if date set to empty string, nothing was called That's why we need
		 * these listener additionally
		 */
		KeyListener keyListener = new KeyListener() {

			public void keyTyped(KeyEvent e) {
			}

			public void keyPressed(KeyEvent e) {
			}

			public void keyReleased(KeyEvent e) {
				JTextFieldDateEditor dateField = (JTextFieldDateEditor) e.getSource();

				if (dateField.getText().trim().length() <= 0 || dateField.isEditValid()) {
					dateSearchSettingsChanged();
				}
			}

		};
		((JTextFieldDateEditor) this.fromDateChooser.getDateEditor()).addKeyListener(keyListener);
		((JTextFieldDateEditor) this.toDateChooser.getDateEditor()).addKeyListener(keyListener);
		/* **************************************** */

		/* ------------------------------------------------------- */
		this.textField.getDocument().addDocumentListener(this);
		this.clearButton.addActionListener(this);
		this.reload.addActionListener(this);
		/* ================================================== */
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
	 */
	public void actionPerformed(ActionEvent e) {
		/* ====================================================== */
		if (this.typeBox.equals(e.getSource())) {
			/* ------------------------------------------------------- */
			if (typeBox.getSelectedItem() != null && !"".equals(typeBox.getSelectedItem())) {
				/* ------------------------------------------------------- */
				this.typeFilter.setFilter(typeBox.getSelectedItem());
				historyTablePanel.getModel().setFilteringEnabled(true, 2);
				/* ------------------------------------------------------- */
			} else
				historyTablePanel.getModel().setFilteringEnabled(false, 2);

			/* ------------------------------------------------------- */
		} else if (this.clearButton.equals(e.getSource())) {
			/* ------------------------------------------------------- */
			this.textField.setText("");
			this.fromDateChooser.setDate(null);
			this.toDateChooser.setDate(null);
			try {
				/* --------------------------------------------- */
				this.typeBox.setSelectedIndex(0);
				/* --------------------------------------------- */
			} catch (Exception ex) {
			}
			/* ------------------------------------------------------- */
		} else if (this.reload.equals(e.getSource())) {
			/* ------------------------------------------------------- */
			HistoryDataAgent da = patientPanel.getHistoryDataAgent();
			
			if (panels.size() > 0) {
				logger.info(
						"BEFORE HistoryData Reload: \n" + da.createLog() + "\n" + panels.get(0).getModel().createLog());
				
				da.reload();
				
				logger.info(
						"AFTER HistoryData Reload: \n" + da.createLog() + "\n" + panels.get(0).getModel().createLog());				
			} else {
				logger.info("No Panel Shown");
			}


			/* ------------------------------------------------------- */
		}
		// historyTablePanel.updateTable();

		updatePanels();

		// model.fireTableDataChanged();
		/* ====================================================== */
	}

	/**
	 * update all HistoryTablePanels in the HistoryViewTap
	 */
	private void updatePanels() {
		for (HistoryTablePanel panel : panels) {
			panel.updateTable();

		}
	}

	/**
	 * install a search filter to all HistoryTablePanels
	 * 
	 * @param filter
	 *            the filter to install
	 * @param col
	 *            the column of the table on with the filter will be installed
	 */
	protected void installFilter(TableFilter filter, int col) {
		for (HistoryTablePanel panel : panels) {
			panel.getModel().installFilter(filter, col);
		}
	}

	/**
	 * enable or disable filter on a table column
	 * 
	 * @param enabled
	 *            if true enable filter, if false disable filter
	 * @param col
	 *            the column of the table where the filter is enable or disable
	 */
	private void enableFilter(boolean enabled, int col) {
		for (HistoryTablePanel panel : panels) {
			panel.getModel().setFilteringEnabled(enabled, col);
		}
	}

	/**
	 * 
	 * @see java.beans.PropertyChangeListener#propertyChange(java.beans.PropertyChangeEvent)
	 */
	public void propertyChange(PropertyChangeEvent evt) {
		if (!"date".equals(evt.getPropertyName()))
			return;

		dateSearchSettingsChanged();
	}

	protected void dateSearchSettingsChanged() {
		/* ====================================================== */
		Date fromDate = null;
		Date toDate = null;
		Date today = new Date();

		// if (this.fromDateChooser.equals(evt.getSource())) {
		/* ------------------------------------------------------- */
		fromDate = fromDateChooser.getDate();
		/* ------------------------------------------------------- */
		// }
		// if (this.toDateChooser.equals(evt.getSource())) {
		/* ------------------------------------------------------- */
		toDate = toDateChooser.getDate();
		// }

		/* ------------------------------------------------------- */
		// from field is filled, to field isn't
		//
		// select all incidents from selected date until now
		/* ------------------------------------------------------- */
		if (fromDate != null && toDate == null) {
			/* ------------------------------------------------------- */
			toDate = today;
			/* ------------------------------------------------------- */
		}

		/* **************************************** */
		/*
		 * this case must not be executed, because otherwise it might not be
		 * possible to reset the from date to null
		 */
		/* **************************************** */
		// } else
		//
		// /* ------------------------------------------------------- */
		// // to field is filled, from field isn't
		// //
		// // select all incidents from the first incident upto the selected
		// // date
		// /* ------------------------------------------------------- */
		// if (toDate != null && fromDate == null) {
		// /* ------------------------------------------------------- */
		// int row = this.historyTablePanel.getModel().getRowCount();
		//
		// try {
		// fromDate =
		// this.patientPanel.getHistoryDataAgent().getIncidentByRow(row-1).getIncidentDate();
		// } catch (Exception e) {}
		// /* ------------------------------------------------------- */
		// }
		/* **************************************** */

		/* ------------------------------------------------------- */
		// if both are filled
		//
		// select all incidents that are in the enclosed periode
		/* ------------------------------------------------------- */
		// flip the dates if the order is mixed up
		// from - to
		/* ------------------------------------------------------- */
		if (toDate != null && fromDate != null && toDate.after(fromDate)) {
			/* ------------------------------------------------------- */
			Date tmp = toDate;
			toDate = fromDate;
			fromDate = tmp;
			/* ------------------------------------------------------- */
		}
		/* ------------------------------------------------------- */
		// move the date to the morning to get the incidents for the whole day
		/* ------------------------------------------------------- */
		if (fromDate != null)
			fromDate = DateUtil.move2Midnight(fromDate);
		/* ------------------------------------------------------- */
		// move the date to the midnight to get the incidents for the whole day
		/* ------------------------------------------------------- */
		if (toDate != null)
			toDate = DateUtil.move2Morning(toDate);
		/* ------------------------------------------------------- */
		this.dateFilter.setFromFilter(fromDate);
		this.dateFilter.setToFilter(toDate);
		/* ------------------------------------------------------- */
		// enable filter
		/* ------------------------------------------------------- */
		if (fromDateChooser.getDate() == null && toDateChooser.getDate() == null)
			enableFilter(false, 0);
		else
			enableFilter(true, 0);
		/* ------------------------------------------------------- */
		// historyTablePanel.updateTable();
		updatePanels();
		/* ====================================================== */
	}

	public void changedUpdate(DocumentEvent e) {
		/* ====================================================== */
		triggerTextEvent();
		/* ====================================================== */
	}

	public void insertUpdate(DocumentEvent e) {
		/* ====================================================== */
		triggerTextEvent();
		/* ====================================================== */
	}

	public void removeUpdate(DocumentEvent e) {
		/* ====================================================== */
		triggerTextEvent();
		/* ====================================================== */
	}

	private void triggerTextEvent() {

		/* ================================================== */
		/* ------------------------------------------------------- */
		if (textField.getText() != null && !"".equals(textField.getText().trim())) {
			this.textFilter.setFilter(textField.getText());
			enableFilter(true, 3);
		} else
		{
			enableFilter(false, 3);
		}
		//	enableFilter(false, 3);
		// historyTablePanel.updateTable();
		updatePanels();
		/* ================================================== */
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * lu.tudor.santec.gecamed.patient.gui.PatientViewTab#setPatient(lu.tudor.
	 * santec.gecamed.patient.ejb.entity.beans.Patient)
	 */
	@Override
	public void setPatient(Patient patient) {
		/* ====================================================== */
		try {
			historyTab.setSelectedIndex(0);			
		} catch (Exception e) {
			logger.warn("Error activating History Tab", e);
		}
		/* ====================================================== */
	}

	public Incident getSelectedIncident() {
		((HistoryTablePanel) this.historyTab.getSelectedComponent()).getSelectedIncident();
		return null;
	}

	public void fetchTypes() {

		if (typetoShow == null) {
			filterList.clear();
			historyTab.removeAll();
			historytabEntries.clear();
			panels.clear();
			String val = (String) PatientManagerModule.getInstance().patientSettings.getValue(IncidentManager.HISTORY_TABS);
			if (val != null) {
				String[] values = val.split("\n");

				for (int i = 0; i < values.length; i++) {
					//System.out.println("-------" + values[i]);
					HistoryTabEntryConfig entry = new HistoryTabEntryConfig(values[i]);
					if (entry.getId() != null) {

						if (entry.isEnabled()) {
							HistoryTablePanel customTP = new HistoryTablePanel(patientPanel, false);

							if (!entry.getFilters().equals("")) {

								String[] typesID = entry.getFilters().split(":");
								HistoryTypeFilter filter = new HistoryTypeFilter();

								for (String typ : typesID) {
									filter.addFilter(typ);
								}

								filterList.addElement(filter);
								// filter.setFilter(typesID[0]);
								customTP.getModel().installFilter(filter, 2);

								customTP.getModel().setFilteringEnabled(true, 2);
								historyTab.addTab(entry.getId(), customTP);
							} else {
								historyTab.addTab(entry.getId(), customTP);
								filterList.addElement(new HistoryTypeFilter());
							}

							panels.add(customTP);
							historytabEntries.add(entry);

						} else {
							// filterList.addElement(new HistoryTypeFilter());
						}

					}
				}

			}
		} else {
			filterList.clear();
			historyTab.removeAll();
			historytabEntries.clear();
			panels.clear();

			HistoryTabEntryConfig entry = new HistoryTabEntryConfig("Forms");

			HistoryTablePanel customTP = new HistoryTablePanel(patientPanel);

			HistoryTypeFilter filter = new HistoryTypeFilter();

			filter.addFilter(typetoShow);

			filterList.addElement(filter);
			// filter.setFilter(typesID[0]);
			customTP.getModel().installFilter(filter, 2);

			customTP.getModel().setFilteringEnabled(true, 2);
			historyTab.addTab(entry.getId(), customTP);

			historyTab.setUI(new javax.swing.plaf.metal.MetalTabbedPaneUI() {
				@Override
				protected int calculateTabAreaHeight(int tabPlacement, int horizRunCount, int maxTabHeight) {

					return 0;

				}

				protected void paintTabArea(Graphics g, int tabPlacement, int selectedIndex) {
				}
			});

			panels.add(customTP);
			historytabEntries.add(entry);
			historyTab.repaint();
		}
	}

	private void initTypeButtons() {

		HistoryTabEntryConfig hist = historytabEntries.elementAt(historyTab.getSelectedIndex());

		if (!hist.getFilters().equals("")) {
			String[] enabledTypesID = hist.getFilters().split(":");

			for (JToggleButton but : buttonsList) {
				for (String tmp : enabledTypesID) {
					if (tmp.charAt(0) == ' ' && tmp.charAt(1) == ' ') {
						tmp.trim();
						textField.setText(tmp);
						this.textFilter.setFilter(tmp);
						
						enableFilter(true, 3);
					} else {
						but.setSelected(false);
						if (tmp.equals(but.getActionCommand())) {
							but.setSelected(true);
							break;
						}
					}

				}
			}
		} else {
			textField.setText("");
			for (JToggleButton but : buttonsList) {
				but.setSelected(false);
			}
		}

	}

	private void initTabListener() {
		historyTab.addChangeListener(new ChangeListener() {

			public void stateChanged(ChangeEvent paramChangeEvent) {
				// TODO Auto-generated method stub

				// fetchTypes();

				textField.setText("");

				try
				{
					
				HistoryTabEntryConfig hist = historytabEntries.elementAt(historyTab.getSelectedIndex());

				HistoryTypeFilter filter = filterList.elementAt(historyTab.getSelectedIndex());

				filter.clearFilters();

				String[] enabledTypesID = null;

				if (!hist.getFilters().equals("")) {

				
					enabledTypesID = hist.getFilters().split(":");

					for (JToggleButton but : buttonsList) {
						for (String tmp : enabledTypesID) {
							if (tmp.charAt(0) == ' ' && tmp.charAt(1) == ' ') {
								tmp.trim();
								textField.setText(tmp);
							} else {
								but.setSelected(false);
								if (tmp.equals(but.getActionCommand())) {
									but.setSelected(true);
									break;
								}
							}

						}
					}
				} else {
					textField.setText("");

					for (JToggleButton but : buttonsList) {
						but.setSelected(false);
					}
				}

				// updatePanels();

				HistoryTablePanel panel = (HistoryTablePanel) historyTab.getSelectedComponent();
				HistoryTypeFilter filt = filterList.elementAt(historyTab.getSelectedIndex());

				if (filt == null) {
					filt = new HistoryTypeFilter();
				}

				filt.clearFilters();
				if (enabledTypesID != null) {
					for (String str : enabledTypesID) {
						filt.addFilter(str);
					}
				}

				if (filt.size() == 0) {

					enableFilter(false, 2);
					// enableFilter(true, 2);
				}

				else {
					// panel.getModel().clearFilters();
					panel.getModel().installFilter(filt, 2);
					panel.getModel().setFilteringEnabled(true, 2);
				}

				updatePanels();
				}
				catch(Exception ex)
				{
					System.err.println(ex.getMessage());
				}
			}
			
		});
		

	}
}