/*****************************************************************************
 *                                                                           *
 *  Copyright (c) 2010 by SANTEC/TUDOR www.santec.tudor.lu                   *
 *                                                                           *
 *                                                                           *
 *  This library is free software; you can redistribute it and/or modify it  *
 *  under the terms of the GNU Lesser General Public License as published    *
 *  by the Free Software Foundation; either version 2 of the License, or     *
 *  (at your option) any later version.                                      *
 *                                                                           *
 *  This software 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 along with this library; if not, write to the Free Software      *
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA  *
 *                                                                           *
 *****************************************************************************/
package lu.tudor.santec.gecamed.waitingroom.gui;

import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.List;

import javax.swing.BorderFactory;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JTextField;
import javax.swing.border.Border;

import lu.tudor.santec.gecamed.core.gui.GECAMedLists;
import lu.tudor.santec.gecamed.core.gui.MainFrame;
import lu.tudor.santec.gecamed.core.gui.widgets.GECAMedBaseDialog;
import lu.tudor.santec.gecamed.office.ejb.entity.beans.Physician;
import lu.tudor.santec.gecamed.office.ejb.entity.beans.Site;
import lu.tudor.santec.gecamed.waitingroom.ejb.entity.beans.Room;
import lu.tudor.santec.i18n.Translatrix;
import lu.tudor.santec.widgets.gui.form.FormPanel;

/**
 * @author martin.heinemann@tudor.lu
 * 06.05.2008
 * 09:52:09
 *
 *
 * @version
 * <br>$Log: WaitingroomEditDialog.java,v $
 * <br>Revision 1.12  2013-02-19 12:07:34  ferring
 * <br>GECAMedLists changed. Will now automatically load list of all beans
 * <br>
 * <br>Revision 1.11  2011-09-20 13:12:17  troth
 * <br>fix some little bug's:
 * <br>1. add " " -item to the physician select box so that user able to select no physician.
 * <br>2. fix a null-pointer exception if a waiting room have no physician.
 * <br>
 * <br>Revision 1.10  2010-12-03 10:18:07  troth
 * <br>Complete - # 649: Wartesaal nur f�r einen Arzt anzeigen
 * <br>http://santec.tudor.lu/trac/gecamed/ticket/649
 * <br>
 * <br>Revision 1.9  2010-12-02 16:13:02  troth
 * <br>Text Correction
 * <br>
 * <br>Revision 1.8  2010-12-02 16:01:18  troth
 * <br>Add new Function to this Dialog. The name and the color of the waiting room are (pre) set by choosing the physician.
 * <br>
 * <br>Revision 1.7  2010-04-30 13:08:42  hermen
 * <br>added site to waitingroom
 * <br>
 * <br>Revision 1.6  2009-10-13 09:11:02  hermen
 * <br>Add/Delete/Edit Waitingroom are now in the admin-settings.
 * <br>Description of Waitingroom can be changed by user
 * <br>
 * <br>Revision 1.5  2008-12-05 17:34:23  heinemann
 * <br>moved some basic classes to lu.tudor.santec.widgets
 * <br>
 * <br>Revision 1.4  2008-11-12 17:16:33  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.3  2008-09-25 09:43:06  heinemann
 * <br>fixed copyrights
 * <br>
 * <br>Revision 1.2  2008-05-08 09:10:02  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.1  2008-05-07 14:40:35  heinemann
 * <br>*** empty log message ***
 * <br>
 *   
 */
public class WaitingroomEditDialog extends GECAMedBaseDialog implements ActionListener, PropertyChangeListener {

	/**
	 * 
	 */
	private static final long 	serialVersionUID = 1L;
	private FormPanel 			mainPanel;
	private JTextField 			nameField;
	private JTextField 			descField;
	private JComboBox 			physicianBox;
	private JComboBox 			siteBox;
	private Room 				room;
	private List<Physician> 	physicianList;
	private List<Site> 			siteList = new ArrayList<Site>();
	private JButton 			colorButton;

	/**
	 * @param title
	 * @param createButtons
	 */
	private WaitingroomEditDialog(String title, boolean createButtons) {
		/* ================================================== */
		super(title, createButtons);
		/* ================================================== */
	}
	
	
	/**
	 * 
	 */
	public WaitingroomEditDialog() {
		/* ================================================== */
		this(Translatrix.getTranslationString("waitingroom.edit"), true);
		/* ------------------------------------------------------- */
		this.enableOkKeyMapping(true);
		this.enableCancelKeyMapping(true);
		/* ------------------------------------------------------- */
		buildPanel();
		initListener();
		
		fillPhysicianBox();
		fillSiteBox();
		/* ================================================== */
	}
	
	
	public void showDialog(Room room) {
		/* ================================================== */
		this.room = room;
		/* ------------------------------------------------------- */
		// set the data
		/* ------------------------------------------------------- */
		this.nameField.setText(this.room.getName());
		this.descField.setText(this.room.getDescription());
		/* ------------------------------------------------------- */
		// select the physician
		/* ------------------------------------------------------- */
		selectPhysician(room.getPhysicianId());
//		/* ------------------------------------------------------- */
//		// select the site
//		/* ------------------------------------------------------- */
		selectSite(room.getSiteId());
		/* ------------------------------------------------------- */
		// set the color
		/* ------------------------------------------------------- */
		if (room.getColor() != null)
			this.colorButton.setBackground(new Color(room.getColor()));
		this.pack();
		MainFrame.showDialogCentered(this);
		/* ================================================== */
	}
	
	
	public void showDialog(Room room, Physician physician) {
		room.setPhysicianId(physician.getId());
		this.showDialog(room);
	}
	
	
	/**
	 * @param physicianId
	 */
	private void selectPhysician(Integer physicianId) {
		/* ================================================== */
		// find the physician in the list
		/* ------------------------------------------------------- */
		for (Object o : this.physicianList) {
			/* ------------------------------------------------------- */
			Physician p = (Physician) o;
			if (p.getId().equals(physicianId)) {
				this.physicianBox.setSelectedItem(p);
				return;
			}
			/* ------------------------------------------------------- */
		}
		/* ================================================== */
	}
	
	/**
	 * @param siteId
	 */
	private void selectSite(Integer siteId) {
		/* ================================================== */
		// find the site in the list
		/* ------------------------------------------------------- */
		for (Site ag : this.siteList) {
			/* ------------------------------------------------------- */
			if (ag.getId().equals(siteId)) {
				this.siteBox.setSelectedItem(ag);
				return;
			}
			/* ------------------------------------------------------- */
		}
		/* ================================================== */
	}
	

	/**
	 * 
	 */
	private void initListener() {
		/* ================================================== */
		this.okButton.addActionListener(    this);
		this.cancelButton.addActionListener(this);
		/* ------------------------------------------------------- */
		GECAMedLists.addPropertyChangeListener(this, Physician.class);
//		GECAMedLists.addPropertyChangeListener(this, AgendaCalendar.class);
		/* ================================================== */
	}
	
	/**
	 * Gets physicians and calendars to fill the comboboxes
	 */
	private void fillPhysicianBox() {
		/* ================================================== */
		this.physicianList = GECAMedLists.getListCopy(Physician.class);
		/* ------------------------------------------------------- */
		// physicians
		/* ------------------------------------------------------- */
		physicianBox.removeAllItems();
		// add a space char because the physicianBox render create labels 
		physicianBox.addItem(" "); 
		if (physicianList != null)
			for (Physician p : physicianList)
				physicianBox.addItem(p);
		/* ================================================== */
	}
	
	/**
	 * 
	 */
	private void fillSiteBox() {
		/* ================================================== */
		siteBox.removeAllItems();
		siteBox.addItem("");
		siteList.clear();

		/* ------------------------------------------------------- */
		// calendars
		/* ------------------------------------------------------- */
		this.siteList = GECAMedLists.getListCopy(Site.class);
		if (siteList != null) {
		    for (Site s : siteList)
		    	siteBox.addItem(s);
		    
		}
		/* ================================================== */
	}
	
	/**
	 * Show the color chooser for the room color
	 */
	private void showColorChooser() {
		/* ================================================== */
		Color baseColor = Color.WHITE;
		if (this.room.getColor() != null)
			baseColor = new Color(this.room.getColor());
		Color color = JColorChooser.showDialog(colorButton, Translatrix.getTranslationString("consultationRoom.colorChooser"), baseColor);
		/* ------------------------------------------------------- */
		if (color == null)
			return;
		/* ------------------------------------------------------- */
		// set color
		this.colorButton.setBackground(color);
		/* ================================================== */
	}
	
	
	/**
	 * 
	 */
	private void buildPanel() {
		/* ====================================================== */
		this.mainPanel = new FormPanel();
		/* ------------------------------------------------------- */
		this.nameField        = new JTextField(25);
		this.descField 		= new JTextField(25);
		this.physicianBox 	= new JComboBox();
		physicianBox.setRenderer(new DefaultListCellRenderer() {
			private static final long serialVersionUID = 1L;
			private Border selectedBorder = BorderFactory.createLineBorder(Color.BLUE, 2);
			@Override
			public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
				JLabel c = (JLabel)super.getListCellRendererComponent(list, value, index, isSelected,
						cellHasFocus);
				c.setOpaque(true);
				try {
        		        	if (isSelected) {
        		        	    c.setBackground(new Color(((Physician)value).getColor()).brighter());
        		        	    c.setBorder(selectedBorder);
        		        	}
        		        	else {
        		        	    c.setBackground(new Color(((Physician)value).getColor()));
        		        	    c.setBorder(null);
        		        	}
				} catch (Exception e) {
					// this render the " "-item in the box
					c.setBackground(new JLabel().getBackground());
				}
				return c;
			}
        });
		physicianBox.addActionListener(new ActionListener() {
			
			public void actionPerformed(ActionEvent e) {
				
				if (physicianBox.getSelectedItem() != null && !physicianBox.getSelectedItem().equals(" "))
				{
					physicianBox.setBackground(new Color(((Physician) physicianBox.getSelectedItem()).getColor()));
					// set the name of the waitingroom to the name of the physician
					nameField.setText(((Physician) physicianBox.getSelectedItem()).getName() + ", " + ((Physician) physicianBox.getSelectedItem()).getFirstName());
					// set the color of the waitingroom to the color of the physician
					colorButton.setBackground(new Color (((Physician) physicianBox.getSelectedItem()).getColor()));
				}else{
					// set the default values when empty entry are choose
					physicianBox.setBackground(Color.WHITE);
					// set the name of the waitingroom to the name of the physician
					nameField.setText("");
					// set the color of the waitingroom to the color of the physician
					colorButton.setBackground(Color.WHITE);
				}
			}
		});
		this.siteBox 	= new JComboBox();
		this.colorButton 	= new JButton();
		/* ------------------------------------------------------- */
		colorButton.setPreferredSize(new Dimension(40, 15));
		colorButton.addActionListener(this);
		/* ------------------------------------------------------- */
		mainPanel.addLine(Translatrix.getTranslationString("core.physician"), physicianBox);
		//mainPanel.addLine(Translatrix.getTranslationString("core.name"), nameField);
		//mainPanel.addSeparator();
		
		mainPanel.addSeparator();
		mainPanel.addGap();
		mainPanel.addLine(Translatrix.getTranslationString("core.name"), nameField);
		mainPanel.addLine(Translatrix.getTranslationString("waitingroom.description"), descField);
		//mainPanel.addLine(Translatrix.getTranslationString("core.physician"), physicianBox);
		
		if (GECAMedLists.getListReference(Site.class) != null 
				&& GECAMedLists.getListReference(Site.class).size() > 0) {
		    mainPanel.addGap();
		    mainPanel.addLine(Translatrix.getTranslationString("office.site"), siteBox);
		}
		
		mainPanel.addGap();
		mainPanel.addLine(Translatrix.getTranslationString("waitingroom.color"), colorButton);
		/* ------------------------------------------------------- */
		mainPanel.setOpaque(false);
		
		this.addMainPanel(mainPanel);
		/* ====================================================== */
	}


	public void actionPerformed(ActionEvent e) {
		/* ====================================================== */
		if (this.okButton.equals(e.getSource())) {
			/* ------------------------------------------------------- */
			// copy the data from the fields to the room object
			/* ------------------------------------------------------- */
			
			if(this.nameField.getText().equals("")) this.room.setName("new Waitingroom");
			else this.room.setName(this.nameField.getText());
			this.room.setDescription(this.descField.getText());
			/* ------------------------------------------------------- */
			// the physician
			/* ------------------------------------------------------- */
			Object physO = this.physicianBox.getSelectedItem();
			if (physO != null && physO instanceof Physician)
				room.setPhysicianId(((Physician) physO).getId());
			else
				room.setPhysicianId(null);
			/* ------------------------------------------------------- */
			// the site
			/* ------------------------------------------------------- */
			Object calO = this.siteBox.getSelectedItem();
			if (calO != null && calO instanceof Site)
				room.setSiteId(((Site) calO).getId());
			else
				room.setSiteId(null);
			/* ------------------------------------------------------- */
			// set the color
			this.room.setColor(((Color)this.colorButton.getBackground()).getRGB());
		}
		if (this.cancelButton.equals(e.getSource())) {
			/* ------------------------------------------------------- */
			this.room = null;
			/* ------------------------------------------------------- */
		}
		if (colorButton.equals(e.getSource())) {
			/* ------------------------------------------------------- */
			showColorChooser();
			/* ------------------------------------------------------- */
		}
		/* ====================================================== */
	}

	/**
	 * Retuns the modified Room object. Null if nothing changed or escape
	 * 
	 * @return
	 */
	public Room getRoom() {
		/* ================================================== */
		return this.room;
		/* ================================================== */
	}
	
	
	public void propertyChange(PropertyChangeEvent evt) {
		/* ====================================================== */
		if (evt.getPropertyName().equals(Site.class.getSimpleName())) {
			/* ------------------------------------------------------- */
			fillSiteBox();
			/* ------------------------------------------------------- */
		}
		if (evt.getPropertyName().equals(Physician.class.getSimpleName())) {
			/* ------------------------------------------------------- */
			fillPhysicianBox();
			/* ------------------------------------------------------- */
		}
	}
}