/*******************************************************************************
 * 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.waitingroom.gui.widgets;

import java.awt.BorderLayout;
import java.awt.Component;
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 java.awt.event.WindowEvent;
import java.text.DateFormat;
import java.util.Collection;
import java.util.Date;

import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;

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

import lu.tudor.santec.gecamed.core.gui.GECAMedModule;
import lu.tudor.santec.gecamed.core.gui.MainFrame;
import lu.tudor.santec.gecamed.core.gui.utils.GECAMedGuiUtils;
import lu.tudor.santec.gecamed.core.gui.utils.LineColorListRenderer;
import lu.tudor.santec.gecamed.core.gui.widgets.DateTimeChooser;
import lu.tudor.santec.gecamed.core.gui.widgets.GECAMedBaseDialog;
import lu.tudor.santec.gecamed.core.gui.widgets.IntegerField;
import lu.tudor.santec.gecamed.core.gui.widgets.NamedComponent;
import lu.tudor.santec.gecamed.patient.ejb.entity.beans.Patient;
import lu.tudor.santec.gecamed.waitingroom.ejb.entity.beans.Queue;
import lu.tudor.santec.gecamed.waitingroom.ejb.entity.beans.Reason;
import lu.tudor.santec.gecamed.waitingroom.ejb.entity.beans.Room;
import lu.tudor.santec.gecamed.waitingroom.gui.WaitingroomModule;
import lu.tudor.santec.i18n.Translatrix;
import lu.tudor.santec.jtimechooser.JTimeChooser;

/**
 * @author martin.heinemann@tudor.lu
 * 26.02.2008
 * 14:48:43
 *
 *
 * @version
 * <br>$Log: SelectWaitingroomDialog.java,v $
 * <br>Revision 1.8  2013-12-27 18:09:27  donak
 * <br>Cleanup of imports
 * <br>
 * <br>Revision 1.7  2010-03-19 16:47:57  hermen
 * <br>http://santec.tudor.lu/trac/gecamed/ticket/421
 * <br>
 * <br>Revision 1.6  2008-09-25 09:43:08  heinemann
 * <br>fixed copyrights
 * <br>
 * <br>Revision 1.5  2008-07-04 13:38:29  heinemann
 * <br>complete - # 159: Add notes to entries of the waitingroom
 * <br>http://santec.tudor.lu/trac/gecamed/ticket/159
 * <br>
 * <br>Revision 1.4  2008-05-08 09:10:02  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.3  2008-05-07 14:41:26  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.2  2008-03-11 17:17:11  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.1  2008-02-27 08:26:49  heinemann
 * <br>*** empty log message ***
 * <br>
 *   
 */
public class QueueEditDialog extends GECAMedBaseDialog{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static final Reason NO_REASON = new Reason("---");
	private static Collection<Room> rooms;
	private static Collection<Reason> reasons;
	private JList<Room> list;
	private Room selectedRoom;
	private JTextField commentField;
	private Date date;
	private JPanel editPanel;
	private JTimeChooser timeChooser;
	private IntegerField kilometerField;
	private JCheckBox isVisit;
	private NamedComponent kilometerNC;
	private JLabel dateLabel;
	private JComboBox<Reason> reason;
	
	DateFormat df = GECAMedGuiUtils.getDateFormat(false);
	private Queue queue;
	
	
	public QueueEditDialog() {
		/* ================================================== */
		this(Translatrix.getTranslationString("waitingroom.selectroom"));
		/* ================================================== */
	}
	
	
	/**
	 * @param title
	 */
	public QueueEditDialog(String title) {
		/* ================================================== */
		super(title, true);
		showHeader(true);
		setHeaderIcon(WaitingroomModule.getIcon(WaitingroomModule.MOVE_2_WAITINGROOM));
		initDialog();
		/* ================================================== */
	}

	/**
	 * Set the rooms to display
	 * @param rooms
	 */
	public static void setRooms(Collection<Room> r) {
		/* ================================================== */
		rooms = r;
		/* ================================================== */
	}
	
	/**
	 * Set the rooms to display
	 * @param rooms
	 */
	public static void setReasons(Collection<Reason> r) {
		/* ================================================== */
		reasons = r;
		/* ================================================== */
	}
	
	
	/**
	 * Show the dialog
	 * 
	 * @param patient
	 */
	public Queue showDialog(Queue q) {
		
		this.reason.removeAllItems();
		this.reason.addItem(NO_REASON);
		if (reasons != null) {
			for (Reason r : reasons) {
				this.reason.addItem(r);
			} 
			
		}
		/* ================================================== */
		this.queue = q;
		this.setDate(q.getStartDate());
		this.commentField.setText(q.getDescription());
		if (q.getKilometers() != null) {
			this.kilometerField.setValue(q.getKilometers());			
		} else {
			this.kilometerField.setValue(0);
		}
		
		if (q.getIsVisit() != null && q.getIsVisit()) {
			this.kilometerField.setEnabled(true);
			this.kilometerNC.setEnabled(true);
			this.isVisit.setSelected(true);			
		} else {
			this.kilometerField.setEnabled(false);
			this.kilometerNC.setEnabled(false);
			this.isVisit.setSelected(false);			
		}
		
		if (q.getPatientName() != null) {
			this.setHeaderTitle(q.getPatientName());
		}
		/* ------------------------------------------------------- */
		this.list.setListData(this.rooms.toArray(new Room[rooms.size()]));

		/* ------------------------------------------------------- */
		this.setSize(800, 500);
	
		list.setSelectedIndex(0);
		if (q.getRoomId() != null) {
			try {
				for (int i = 0; i < list.getModel().getSize(); i++) {
					if (q.getRoomId().equals(((Room)list.getModel().getElementAt(i)).getId())) {
						list.setSelectedIndex(i);
						break;
					}
				}
			} catch (Exception e) {}
		} else {
			try {
				for (int i = 0; i < list.getModel().getSize(); i++) {
					if (GECAMedModule.getCurrentPhysician().getId().equals(((Room)list.getModel().getElementAt(i)).getPhysicianId())) {
						list.setSelectedIndex(i);
						break;
					}
				}
			} catch (Exception e) {}			
		}
		
		reason.setSelectedIndex(0);
		if (q.getReason() != null) {
			try {
				for (int i = 0; i < reason.getModel().getSize(); i++) {
					if (q.getReason().equals(((Reason)reason.getModel().getElementAt(i)).getId())) {
						reason.setSelectedIndex(i);
						break;
					}
				}
			} catch (Exception e) {}		
		}
	
		list.requestFocus();
		
		MainFrame.showDialogCentered(this);
		
		if (this.getButtonOption() == CANCEL_OPTION) {
			return null;
		}
		
		return getQueue();
		/* ================================================== */
	}
	
//	/**
//	 * Show the dialog
//	 * 
//	 * @param patient
//	 */
//	public void showDialog(Patient patient, Date date) {
//		/* ================================================== */
//		this.setDate(date);
//		this.commentField.setText("");
//		this.kilometerField.setValue(0);
//		this.kilometerField.setEnabled(false);
//		this.kilometerNC.setEnabled(false);
//		this.isVisit.setSelected(false);
//		
//		if (patient != null) {
//			this.setHeaderTitle(patient.toShortString());
//		}
//		/* ------------------------------------------------------- */
//		this.list.setListData(this.rooms.toArray(new Room[rooms.size()]));
//		/* ------------------------------------------------------- */
////		this.pack();
//		this.setSize(800, 400);
//		list.requestFocus();
//	
//		list.setSelectedIndex(0);
//		try {
//		    for (int i = 0; i < list.getModel().getSize(); i++) {
//			if (GECAMedModule.getCurrentPhysician().getId().equals(((Room)list.getModel().getElementAt(i)).getPhysicianId())) {
//			    list.setSelectedIndex(i);
//			    break;
//			}
//		    }
//		} catch (Exception e) {}
//		
//		
//		MainFrame.showDialogCentered(this);
//		/* ================================================== */
//	}
	
	
	private void setDate(Date date) {
		this.date = date;
		this.dateLabel.setText(Translatrix.getTranslationString("waitingwoom.queue.date") + " " + df.format(date));
		this.timeChooser.setTime(date);	
	}


	/**
	 * 
	 */
	private void initDialog() {
		/* ====================================================== */
		
		this.headerLabel.setVerticalAlignment(SwingConstants.CENTER);
		
		this.list = new JList<Room>();
		JScrollPane paine = new JScrollPane(list);
		/* ------------------------------------------------------- */
		list.setCellRenderer(new RoomListRenderer());
		
		CellConstraints cc = new CellConstraints();
		
		this.editPanel = new JPanel(new FormLayout(
				"2dlu, pref:grow, 2dlu, pref, 2dlu, pref", 
				"2dlu, pref, 2dlu, pref, 2dlu, pref, 2dlu, pref, 2dlu, pref, 2dlu, fill:100dlu:grow"));
		
		
		this.dateLabel = new JLabel(); 
		this.editPanel.add(this.dateLabel, cc.xy(2,2));
		
		this.timeChooser = new JTimeChooser();
		this.timeChooser.setEnabledWithDoubleClick(false);
		this.timeChooser.setShowSeconds(false);
		this.editPanel.add(new NamedComponent(Translatrix.getTranslationString("waitingwoom.queue.time"), this.timeChooser), cc.xy(2,4));

		this.isVisit = new JCheckBox();
		this.isVisit.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				kilometerField.setEnabled(isVisit.isSelected());
				kilometerNC.setEnabled(isVisit.isSelected());
			}
		});
		this.editPanel.add(new NamedComponent(Translatrix.getTranslationString("waitingwoom.queue.isVisit"), this.isVisit), cc.xy(4,4));

		this.kilometerField = new IntegerField(4);
		this.kilometerNC = new NamedComponent(Translatrix.getTranslationString("waitingwoom.queue.kilometers"), this.kilometerField);
		this.editPanel.add(this.kilometerNC, cc.xy(6,4));

		this.reason = new JComboBox<Reason>();
		this.reason.addItem(NO_REASON);
		this.editPanel.add(new NamedComponent(Translatrix.getTranslationString("waitingwoom.queue.reason"), this.reason), cc.xyw(2,6,5));
		
		
		this.commentField = new JTextField();
		this.editPanel.add(new NamedComponent(Translatrix.getTranslationString("waitingwoom.queue.comment"), this.commentField), cc.xyw(2,8,5));
		
		this.editPanel.add(new JLabel(Translatrix.getTranslationString("waitingroom")), cc.xyw(2,10,5));
		
		this.editPanel.add(paine, cc.xyw(2,12,5));
		
		/* ------------------------------------------------------- */
		this.add(this.editPanel, BorderLayout.CENTER);
		/* ------------------------------------------------------- */
		// textfield for comment
		/* ------------------------------------------------------- */
//		this.add(commentField, BorderLayout.SOUTH);
		/* ------------------------------------------------------- */
		// mouse and key listener
		/* ------------------------------------------------------- */
		KeyAdapter key = new KeyAdapter() {

			/* (non-Javadoc)
			 * @see java.awt.event.KeyAdapter#keyPressed(java.awt.event.KeyEvent)
			 */
			@Override
			public void keyPressed(KeyEvent e) {
				/* ====================================================== */
				if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
					selectedRoom = null;
					QueueEditDialog.this.setVisible(false);
					return;
				}
				/* ------------------------------------------------------- */
				// leave out the arrow keys
				/* ------------------------------------------------------- */
				if (e.getKeyCode() == KeyEvent.VK_UP || e.getKeyCode() == KeyEvent.VK_DOWN
						|| e.getKeyCode() == KeyEvent.VK_RIGHT || e.getKeyCode() == KeyEvent.VK_LEFT)
					return;
				/* ------------------------------------------------------- */
				// ENTER  - select the room
				/* ------------------------------------------------------- */
				if (e.getKeyCode() == KeyEvent.VK_ENTER) {
					selectRoom(list.getSelectedIndex());
					return;
				}
				
				/* ------------------------------------------------------- */
				// try to find the row according to the key
				/* ------------------------------------------------------- */
				try {
					/* ------------------------------------------------------- */
					char c =  e.getKeyChar();
					selectRoom(Integer.parseInt((""+c)));
					/* ------------------------------------------------------- */
				} catch (Exception ex) {
//					ex.printStackTrace();
				}
				/* ====================================================== */
			}
		};
		
		list.addKeyListener(key);
		//commentField.addKeyListener(key);
		this.addKeyListener(key);
		
		
		/* ------------------------------------------------------- */
		list.addMouseListener(new MouseAdapter() {

			/* (non-Javadoc)
			 * @see java.awt.event.MouseAdapter#mousePressed(java.awt.event.MouseEvent)
			 */
			@Override
			public void mousePressed(MouseEvent e) {
				/* ====================================================== */
				if (e.getClickCount() == 2 && SwingUtilities.isLeftMouseButton(e)) {
					/* ------------------------------------------------------- */
					selectRoom(list.getSelectedIndex());
					/* ------------------------------------------------------- */
				}
				/* ====================================================== */
			}
		});
		/* ====================================================== */
		
		this.addWindowListener(new java.awt.event.WindowAdapter() {
			public void windowOpened(WindowEvent e) {
				list.requestFocusInWindow();
			}
		});
	}
	
	
	/**
	 * Selects the room and closes the dialog
	 * 
	 * @param index
	 */
	private void selectRoom(int index) {
		/* ================================================== */
		try {
			/* ------------------------------------------------------- */
			if (index >= list.getModel().getSize() || index < 0)
				return;
			
			list.setSelectedIndex(index);
			this.selectedRoom = (Room) list.getSelectedValue();
			if (selectedRoom != null)
				this.setVisible(false);
			/* ------------------------------------------------------- */
		} catch (Exception e) {
			/* ------------------------------------------------------- */
			e.printStackTrace();
			/* ------------------------------------------------------- */
		}
		/* ================================================== */
	}
	
	
	private Room getSelectedRoom() {
		/* ================================================== */
		return (Room) list.getSelectedValue();
		/* ================================================== */
	}
	
	private String getComment() {
		/* ================================================== */
		return this.commentField.getText();
		/* ================================================== */
	}
	
	private Date getDateTime() {
		/* ================================================== */
		return this.timeChooser.getDateWithTime(this.date);
		/* ================================================== */
	}
	
	private Integer getKilometers() {
		/* ================================================== */
		Integer kilos = this.kilometerField.getValueInteger();
		return kilos;
		/* ================================================== */
	}
	
	private Boolean isVisit() {
		/* ================================================== */
		return this.isVisit.isSelected();
		/* ================================================== */
	}
	
	private Reason getReason() {
		/* ================================================== */
		return (Reason) this.reason.getSelectedItem();
		/* ================================================== */
	}
	
	public Queue getQueue() {
		/* ================================================== */
		if (getSelectedRoom() == null) {
			return null; 			
		}
		
		this.queue.setDescription(getComment());
		this.queue.setIsVisit(isVisit());
		this.queue.setKilometers(getKilometers());
		this.queue.setStartDate(getDateTime());
		
		this.queue.setRoomId(getSelectedRoom().getId());
		this.queue.setReason(getReason().getId());
		
		return queue;
		/* ================================================== */
	}
	
	/**
	 * @author martin.heinemann@tudor.lu
	 * 26.02.2008
	 * 15:16:17
	 *
	 *
	 * @version
	 * <br>$Log: SelectWaitingroomDialog.java,v $
	 * <br>Revision 1.8  2013-12-27 18:09:27  donak
	 * <br>Cleanup of imports
	 * <br>
	 * <br>Revision 1.7  2010-03-19 16:47:57  hermen
	 * <br>http://santec.tudor.lu/trac/gecamed/ticket/421
	 * <br>
	 * <br>Revision 1.6  2008-09-25 09:43:08  heinemann
	 * <br>fixed copyrights
	 * <br>
	 * <br>Revision 1.5  2008-07-04 13:38:29  heinemann
	 * <br>complete - # 159: Add notes to entries of the waitingroom
	 * <br>http://santec.tudor.lu/trac/gecamed/ticket/159
	 * <br>
	 * <br>Revision 1.4  2008-05-08 09:10:02  heinemann
	 * <br>*** empty log message ***
	 * <br>
	 * <br>Revision 1.3  2008-05-07 14:41:26  heinemann
	 * <br>*** empty log message ***
	 * <br>
	 * <br>Revision 1.2  2008-03-11 17:17:11  heinemann
	 * <br>*** empty log message ***
	 * <br>
	 * <br>Revision 1.1  2008-02-27 08:26:49  heinemann
	 * <br>*** empty log message ***
	 * <br>
	 *   
	 */
	class RoomListRenderer extends LineColorListRenderer {

		/**
		 * 
		 */
		private static final long serialVersionUID = 1L;
		
		
		public RoomListRenderer() {
			/* ================================================== */
//			this.setFont(new Font(this.getFont().getName(), Font.PLAIN, 18));
			/* ================================================== */
		}
		
		/* (non-Javadoc)
		 * @see lu.tudor.santec.gecamed.core.gui.utils.LineColorListRenderer#getListCellRendererComponent(javax.swing.JList, java.lang.Object, int, boolean, boolean)
		 */
		@Override
		public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
			/* ====================================================== */
			if (value instanceof Room) {
				/* ------------------------------------------------------- */
				
				String s = "" + index +". " + ((Room) value).getName();
				
				return super.getListCellRendererComponent(list, s, index, isSelected,
						cellHasFocus);
				/* ------------------------------------------------------- */
			}
			return super.getListCellRendererComponent(list, value, index, isSelected,
					cellHasFocus);
			/* ====================================================== */
		}
		
		
		
		
		
	}
	

}
