package lu.tudor.santec.gecamed.patient.gui.patientlist;
///*******************************************************************************
// * 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.patientlist;
//
//import java.awt.BorderLayout;
//import java.awt.Color;
//import java.awt.Cursor;
//import java.awt.event.ActionEvent;
//import java.awt.event.KeyEvent;
//import java.awt.event.KeyListener;
//import java.awt.event.MouseEvent;
//import java.awt.event.MouseListener;
//import java.beans.PropertyChangeEvent;
//import java.beans.PropertyChangeListener;
//import java.util.ArrayList;
//import java.util.Collection;
//import java.util.Iterator;
//import org.apache.log4j.Level;
//import org.apache.log4j.Logger;
//
//import javax.swing.Action;
//import javax.swing.JButton;
//import javax.swing.JDialog;
//import javax.swing.JScrollPane;
//import javax.swing.JTable;
//import javax.swing.JTextField;
//import javax.swing.border.TitledBorder;
//import javax.swing.event.ListSelectionEvent;
//import javax.swing.event.ListSelectionListener;
//
//import lu.tudor.santec.gecamed.billing.gui.TextWrappingCellRenderer;
//import lu.tudor.santec.gecamed.core.gui.GECAMedAction;
//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.utils.LineColorCellRenderer;
//import lu.tudor.santec.gecamed.core.gui.utils.TableSorter;
//import lu.tudor.santec.gecamed.core.gui.widgets.ModuleHeader;
//import lu.tudor.santec.gecamed.core.utils.ManagerFactory;
//import lu.tudor.santec.gecamed.patient.ejb.entity.beans.Insurance;
//import lu.tudor.santec.gecamed.patient.ejb.entity.beans.Patient;
//import lu.tudor.santec.gecamed.patient.ejb.session.beans.InsuranceBean;
//import lu.tudor.santec.gecamed.patient.ejb.session.beans.PatientAdminBean;
//import lu.tudor.santec.gecamed.patient.ejb.session.interfaces.InsuranceInterface;
//import lu.tudor.santec.gecamed.patient.ejb.session.interfaces.PatientAdminInterface;
//import lu.tudor.santec.gecamed.patient.gui.PatientListModule;
//import lu.tudor.santec.gecamed.patient.gui.PatientManagerModule;
//import lu.tudor.santec.i18n.Translatrix;
//
//
///**
// * Dialog to search for patients without using the search module.
// * used to pick patients for calendar entries or patient relations.
// * 
// * functionality is exactly the same as the search patient module.
// * 
// * @author Johannes Hermen johannes.hermen(at)tudor.lu
// *
// * @version
// * <br>$Log: PatientSearchDialog_Old.java,v $
// * <br>Revision 1.2  2013-07-15 06:18:35  ferring
// * <br>logging changed
// * <br>
// * <br>Revision 1.1  2012-04-12 15:29:57  troth
// * <br>Release new search dialog panel.
// * <br>
// * <br>Revision 1.19  2010-03-12 14:17:42  hermen
// * <br>cleanup of panel layouts and icons
// * <br>
// * <br>Revision 1.18  2008-09-25 09:43:07  heinemann
// * <br>fixed copyrights
// * <br>
// * <br>Revision 1.17  2008-05-28 12:08:11  heinemann
// * <br>*** empty log message ***
// * <br>
// * <br>Revision 1.16  2008-05-27 09:09:11  hermen
// * <br>fixed search RETURN key behavior
// * <br>
// * <br>Revision 1.15  2008-05-27 08:23:50  hermen
// * <br>fixed search in dialog and added new setting
// * <br>
// * <br>Revision 1.14  2008-05-07 14:39:53  heinemann
// * <br>new waitingroom
// * <br>
// * <br>Revision 1.13  2008-04-28 08:05:48  hermen
// * <br>changed patient search to use patient_stub view and bean
// * <br>
// * <br>Revision 1.12  2008-04-14 08:11:58  hermen
// * <br>added option to use big fonts for patient seatrch and reorganized search settings
// * <br>
// * <br>Revision 1.11  2008-01-23 08:30:09  hermen
// * <br>*** empty log message ***
// * <br>
// *
// */
//public class PatientSearchDialog extends JDialog implements PropertyChangeListener, MouseListener {
//
//	private static final long serialVersionUID = 1L;
//	
//	public PatientStubListTableModel patientListTableModel;
//	private TableSorter tableSorter;
//	public JTable patientTable;
//	public PatientAdminInterface manager;
//	private JTextField searchTextField;
//	protected boolean completeList;
//	private String filter = "";
//	private InsuranceInterface insuranceManager;
//	private JScrollPane jsp;
//	private ModuleHeader moduleHeader;
//
//	private Patient patient;
//
//	protected boolean searchChanged = true;
//
//	protected boolean openPatient;
//	
//	private static PatientSearchDialog instance = new PatientSearchDialog();
//
//	@SuppressWarnings("unchecked")
//	public PatientSearchDialog() {
//		super(MainFrame.getInstance(), Translatrix.getTranslationString("PatientList"), true);
//		this.setLayout(new BorderLayout());
//		this.patientListTableModel = new PatientStubListTableModel();
//
//		// Get the type manager
//		manager = (PatientAdminInterface) ManagerFactory.getRemote(PatientAdminBean.class);
//		insuranceManager = (InsuranceInterface) ManagerFactory.getRemote(InsuranceBean.class);
//
//		this.tableSorter = new TableSorter(this.patientListTableModel);
//		
//		this.patientTable = new JTable(this.tableSorter);
//		this.patientTable.addMouseListener(this);
//		this.patientTable.getTableHeader().setReorderingAllowed(false);
//		
//		LineColorCellRenderer renderer = new LineColorCellRenderer();
//		this.patientTable.getColumnModel().getColumn(0).setCellRenderer(renderer);
//		this.patientTable.getColumnModel().getColumn(0).setMinWidth(100);
//		this.patientTable.getColumnModel().getColumn(1).setCellRenderer(renderer);
//		this.patientTable.getColumnModel().getColumn(1).setMinWidth(150);
//		this.patientTable.getColumnModel().getColumn(2).setCellRenderer(renderer);
//		this.patientTable.getColumnModel().getColumn(2).setMinWidth(150);
//		this.patientTable.getColumnModel().getColumn(3).setCellRenderer(renderer);
//		this.patientTable.getColumnModel().getColumn(3).setMinWidth(150);
//		this.patientTable.getColumnModel().getColumn(4).setCellRenderer(renderer);
//		this.patientTable.getColumnModel().getColumn(4).setMinWidth(50);
//		this.patientTable.getColumnModel().getColumn(5).setCellRenderer(renderer);
//		this.patientTable.getColumnModel().getColumn(5).setMinWidth(50);
//		this.patientTable.getColumnModel().getColumn(6).setCellRenderer(new TextWrappingCellRenderer());
//		this.patientTable.getColumnModel().getColumn(6).setMinWidth(350);
//		this.patientTable.getColumnModel().getColumn(7).setCellRenderer(renderer);
//		this.patientTable.getColumnModel().getColumn(7).setMinWidth(50);
//		this.patientTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
//		
//		this.patientTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
//			public void valueChanged(ListSelectionEvent e) {
//				patientTable.scrollRectToVisible(patientTable.getCellRect(patientTable.getSelectedRow(),0,true));
//			}
//		});
//		
//		this.tableSorter.setTableHeader(this.patientTable.getTableHeader());
//		jsp = new JScrollPane(this.patientTable);
//		jsp.setAutoscrolls(true);
//		jsp.setBorder(new TitledBorder(Translatrix.getTranslationString("list.patientList")));
//		jsp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
//
//		
//		this.add(jsp, BorderLayout.CENTER);
//		PatientSearchTableHeader sth = new PatientSearchTableHeader(patientTable);
//		sth.addPropertyChangeListener(this);
//		
//		this.patientTable.addKeyListener(new KeyListener() {
//
//			public void keyTyped(KeyEvent e) {
//				if (e.getKeyCode() == KeyEvent.VK_ENTER) 
//					e.consume();
//			}
//			
//			public void keyPressed(KeyEvent e) {
//				if (e.getKeyCode() == KeyEvent.VK_ENTER) 
//					e.consume();
//			}
//			
//			public void keyReleased(KeyEvent e) {
//				if (e.getKeyCode() == KeyEvent.VK_ENTER) {
//					e.consume();
//					loadPatient();
//				} else if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
//					e.consume();
//					setVisible(false);
//				}
//			}
//		});
//		
//		
//		this.searchTextField = new JTextField(30);
//		this.searchTextField.setToolTipText(Translatrix.getTranslationString("pm.searchHelp"));
//		this.searchTextField.addKeyListener(new KeyListener() {
//			public void keyTyped(KeyEvent e) {
//			}
//			public void keyPressed(KeyEvent e) {
//				/* ================================================== */
//				if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
//					e.consume();
//					setVisible(false);
//				} else if (e.getKeyCode() == KeyEvent.VK_DOWN) {
//				    	openPatient = true;
//					try {
//						int row = patientTable.getSelectedRow();
//						patientTable.setRowSelectionInterval(row+1, row+1);
//					} catch (Exception ee) {
//					}
//				} else if (e.getKeyCode() == KeyEvent.VK_UP) {
//				    	openPatient = true;
//					try {
//						int row = patientTable.getSelectedRow();
//						patientTable.setRowSelectionInterval(row-1, row-1);
//					} catch (Exception ee) {
//					}
//				} else if (e.getKeyCode() == KeyEvent.VK_ENTER) {
//				    if (openPatient || (Boolean) PatientListModule.getInstance().patientListSettingsPlugin.getValue(PatientSearchSettingsPlugin.START_SEARCH_AUTOMATIC)) {
//					loadPatient();					
//				    } else {
//					searchPatients(false);
//				    }
//				    openPatient = true;
//				   // all other keys
//				} else {
//				    if ((Boolean) PatientListModule.getInstance().patientListSettingsPlugin.getValue(PatientSearchSettingsPlugin.START_SEARCH_AUTOMATIC)) {
//					searchPatients(false);
//				    } 
//				    openPatient = false;
//				}
//				/* ================================================== */
//			}
//			public void keyReleased(KeyEvent e) {
//
//			}
//		});
//		
//		
//		GECAMedAction clearAction = new GECAMedAction(null, "list.clear", GECAMedModule.getSmallIcon(GECAMedIconNames.EDIT_CLEAR_RTL), 0 ,false, true, false) {
//			private static final long serialVersionUID = 1L;
//			public void actionPerformed (ActionEvent p_Event) 
//		    {
//				searchTextField.setText("");
//				searchTextField.requestFocus();
//				searchPatients(false);
//		    }
//		};
//		JButton jb = new JButton(clearAction);
//		jb.setText("");
//		jb.setToolTipText((String)clearAction.getValue(Action.SHORT_DESCRIPTION));
//
//		
//		GECAMedAction reloadAction = new GECAMedAction(null, "list.reload", GECAMedModule.getIcon(GECAMedIconNames.RELOAD), 0 ,false, true, false) {
//			private static final long serialVersionUID = 1L;
//			public void actionPerformed (ActionEvent p_Event) 
//		    {
//				setWaitCursor(true);
//				searchPatients(true);
//				setWaitCursor(false);
//		    }
//		};
//		JButton jb2 = new JButton(reloadAction);
//		jb2.setText("");
//		jb2.setToolTipText((String)reloadAction.getValue(Action.SHORT_DESCRIPTION));
//		
//		this.moduleHeader = new ModuleHeader(Translatrix.getTranslationString("PatientList"), PatientManagerModule.getIcon(PatientManagerModule.PATIENTS),Color.WHITE);
//		this.moduleHeader.setHeaderComponent(this.searchTextField);
//		this.moduleHeader.addButton(jb);
//		this.moduleHeader.addButton(jb2);
//		this.add(this.moduleHeader, BorderLayout.NORTH);
//		
//		
//		
//		
////		new Thread() {
////			public void run() {
////				searchPatients(true);
////			}
////		}.start();
//		
//	}
//	
//	@SuppressWarnings("unchecked")
//	public void propertyChange(PropertyChangeEvent evt) {
//		if (evt.getNewValue().equals("")) {
//			filter = "";
//			searchPatients(false);
//			return;
//		}
////		System.out.println("Search for column " + evt.getSource()+ " ("+ evt.getPropertyName() +") with value: " + evt.getNewValue());
//			int column = (Integer) evt.getSource();
//			switch (column) {
//			case 0:
//				filter = "patient.socialSecurityNumber LIKE '" + evt.getNewValue() + "%'";
//				break;
//			case 1:
//				filter = "UPPER(patient.surName) LIKE UPPER('" + evt.getNewValue() + "%')";
//				break;
//			case 2:
//				filter = "UPPER(patient.firstName) LIKE UPPER('" + evt.getNewValue() + "%')";
//				break;
//			case 3:
//				filter = "UPPER(patient.maidenName) LIKE UPPER('" + evt.getNewValue() + "%')";
//				break;
//			case 4:
//				filter = "UPPER(patient.gender) LIKE UPPER('" + evt.getNewValue() + "%')";
//				break;
//			case 5:
//				filter = "";
//				try {
//						Collection<Insurance> insurances = insuranceManager.findInsurancesByAcronym((String)evt.getNewValue());
//						for (Iterator iter = insurances.iterator(); iter
//								.hasNext();) {
//							Insurance element = (Insurance) iter.next();
//							if (filter != "") {
//								filter += " OR ";
//							}
//							filter += " (patient.insuranceID = " + element.getId() + " ) ";
//						}
//					} catch (Exception e1) {
//						logger.log(Level.WARN, "fetching insurance failed", e1);
//					}
//				break;
//			case 6:
//				filter = "";
//				String addrSearch = (String) evt.getNewValue();
//				String[] addrSearchParts = addrSearch.split(" ");
//				for (int i = 0; i < addrSearchParts.length; i++) {
//					try {
//						Long.parseLong(addrSearchParts[i]);
//						if (filter != "") {
//							filter += " AND ";
//						}
//						filter += " (UPPER(address.zip) LIKE UPPER('" + addrSearchParts[i] + "%') ) "; 
//					} catch (Exception e) {
//						if (filter != "") {
//							filter += " AND ";
//						}
//						filter += " (UPPER(address.locality) LIKE UPPER('" + evt.getNewValue() + "%') ) OR " +
//						" (UPPER(address.streetName) LIKE UPPER('" + evt.getNewValue() + "%') )";
//					}
//				}
//				break;
//			case 7:
//				filter = "";
//				try {
//					String status = ((String)evt.getNewValue()).toUpperCase();
//					for (int i = 0; i < Patient.STATES.length; i++) {
//						if (Patient.STATES[i].equals(status)) {
//							filter += " (patient.status = " + i + " ) ";							
//						}
//					}
//				} catch (Exception e1) {
//					logger.log(Level.WARN, "filtering failed", e1);
//				}
//				break;
//			default:
//				break;
//			}
//			searchPatients(false);
//	}
//	
//	@SuppressWarnings("unchecked")
//	private void searchPatients(boolean force) {
//		this.setWaitCursor(true);
//		
//		// store selected patient
//		int currPatient = this.patientListTableModel.getPatientIDforRow(this.patientTable.getSelectedRow());
//		
//		if (searchTextField.getText().length() >= 3 || filter != "") {
//			completeList = false;
////			long now = System.currentTimeMillis();
//			try {
////				System.out.println("Search for: " + searchTextField.getText());
//				patientListTableModel.setPatients(new ArrayList(manager.getPatientStubListBySearchString(searchTextField.getText(), "", filter,
//						(Integer) PatientListModule.getInstance().patientListSettingsPlugin.getValue(PatientSearchSettingsPlugin.SEARCH_LIMIT))));
//				try {
//					try {
//						int row = patientListTableModel.getRowForPatientID(currPatient);
//						patientTable.setRowSelectionInterval(row, row);
//					} catch (Exception e) {
//						try {
//							patientTable.setRowSelectionInterval(0,0);						
//						} catch (Exception e2) {
//						}
//					}
//				} catch (Exception e) {
//				}
//			} catch (Exception e1) {
//				MainFrame.reportServerError(e1);
//			}
////			System.out.println("fetching of " + patientListTableModel.getRowCount() + " patients took " + (System.currentTimeMillis()-now) + " millis");
//		} else if (force || !completeList) {
//			completeList = true;
//			try {
//				// loading complete list
//				patientListTableModel.setPatients(new ArrayList(manager.getPatientStubListBySearchString("", "", filter,
//						(Integer) PatientListModule.getInstance().patientListSettingsPlugin.getValue(PatientSearchSettingsPlugin.SEARCH_LIMIT))));
//				try {
//					int row = patientListTableModel.getRowForPatientID(currPatient);
//					patientTable.setRowSelectionInterval(row, row);
//				} catch (Exception e) {
//					try {
//						patientTable.setRowSelectionInterval(0,0);						
//					} catch (Exception e2) {
//					}
//				}
//			} catch (Exception e1) {
//				MainFrame.reportServerError(e1);
//			}
//		}
//		
//		
//		this.setWaitCursor(false);		
//	}
//
//	/**
//	 * loads the selected patient
//	 */
//	private void loadPatient() {
//		int patientID = -1;
//		this.patient = null;
//		if (this.patientTable.getSelectedRow() == -1) {
//			logger.info("unable to open patient: No patient selected");
//			this.setVisible(false);
//			return;
//		}
//        try {
//        	patientID = this.patientListTableModel.getPatientIDforRow(this.tableSorter.modelIndex(this.patientTable.getSelectedRow()));
//        	this.patient = this.manager.getPatient(patientID);
//		} catch (Exception e1) {
//			logger.info("unable to open patient with ID: " + patientID);
//		}
//		this.setVisible(false);
//	}
//	
//	/* (non-Javadoc)
//	 * @see java.awt.event.MouseListener#mouseClicked(java.awt.event.MouseEvent)
//	 */
//	public void mouseClicked(MouseEvent e)
//    {
//        if ((e.getClickCount() >= 2) &&
//                this.patientTable.equals(e.getSource())) {
//            loadPatient();
//        } 
//    }
//	/* (non-Javadoc)
//	 * @see java.awt.event.MouseListener#mousePressed(java.awt.event.MouseEvent)
//	 */
//	public void mousePressed(MouseEvent e) {
//	}
//	/* (non-Javadoc)
//	 * @see java.awt.event.MouseListener#mouseReleased(java.awt.event.MouseEvent)
//	 */
//	public void mouseReleased(MouseEvent e) {
//	}
//	/* (non-Javadoc)
//	 * @see java.awt.event.MouseListener#mouseEntered(java.awt.event.MouseEvent)
//	 */
//	public void mouseEntered(MouseEvent e) {
//	}
//	/* (non-Javadoc)
//	 * @see java.awt.event.MouseListener#mouseExited(java.awt.event.MouseEvent)
//	 */
//	public void mouseExited(MouseEvent e) {
//	}
//	  
//	/**
//	 * sets the Mousecursor of the MainFrame to a WaitCursor and Back
//	 *
//	 * @param on true=waitcursor false=normalcursor
//	 */
//	private void setWaitCursor(boolean on) {
//		if (on) {
//			this.jsp.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
//			this.patientTable.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
//			this.searchTextField.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
//		} else {
//			this.jsp.setCursor(
//					Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
//			this.patientTable.setCursor(
//					Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
//			this.searchTextField.setCursor(
//					Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
//		}
//	}
//	
//	/**
//	 * shows the dialog and starts the search with the prefilled string.
//	 * @param filter initial filter string for the search
//	 * @return
//	 */
//	public static Patient searchPatient(String filter) {
//		instance.patient = null;
//		instance.searchTextField.setText(filter);
//		instance.searchPatients(true);
//		instance.setSize((int) (MainFrame.getInstance().getWidth()* 0.9), (int) (MainFrame.getInstance().getHeight() * 0.9));
//		MainFrame.showDialogCentered(instance);
//		return instance.patient;
//		
//	}
//	
//}
