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

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.Date;

import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;

import lu.tudor.santec.gecamed.core.gui.GECAMedColors;
import lu.tudor.santec.gecamed.core.gui.GECAMedModule;
import lu.tudor.santec.gecamed.core.gui.utils.ComponentTitledPanel;
import lu.tudor.santec.gecamed.core.gui.utils.GECAMedGuiUtils;
import lu.tudor.santec.gecamed.core.gui.widgets.LimitTextField;
import lu.tudor.santec.gecamed.patient.gui.PatientManagerModule;
import lu.tudor.santec.i18n.Relocalizable;
import lu.tudor.santec.i18n.Translatrix;
import lu.tudor.santec.widgets.gui.ButtonFactory;

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


/**
 * @author Thorsten Roth thorsten.roth(at)tudor.lu
 *
 * @version
 * <br>$Log: AccidentPanel.java,v $
 * <br>Revision 1.5  2013-12-27 18:09:23  donak
 * <br>Cleanup of imports
 * <br>
 * <br>Revision 1.4  2010-09-30 13:03:37  troth
 * <br>Complete - #667
 * <br>http://santec.tudor.lu/trac/gecamed/ticket/667
 * <br>
 * <br>Revision 1.3  2010-09-02 16:16:40  troth
 * <br>Incomplete - # 619: Probleme mit neuer Unfall-Implementierung
 * <br>http://santec.tudor.lu/trac/gecamed/ticket/619
 * <br>
 * <br>Revision 1.2  2010-09-01 11:54:38  troth
 * <br>change data type of accidentNumberTextField from JTextField to LimitTextField
 * <br>
 * <br>Revision 1.1  2010-08-31 13:35:56  troth
 * <br>Incomplete - # 495: Mehrere Unstimmigkeiten mit Unfallnummer (auch #529)
 * <br>http://santec.tudor.lu/trac/gecamed/ticket/495
 * <br>and Tickets 529, 613
 * <br>and new/redesign of AccidentPanel
 * <br>
 */
public class AccidentPanel extends JPanel implements ItemListener, ActionListener, PropertyChangeListener, Relocalizable
	{
	
	private static final long 		serialVersionUID = 1L;
	
	private ComponentTitledPanel	accidentPanel;
	private JCheckBox				accidentCheckBox;
	private JPanel					accidentComponentPanel;
	
	private JButton					accidentSelectionButton;
	
	private JLabel					accidentNumberLabel;
	private JTextField				accidentNumberTextField;
	private JTextField				accidentNumberTextFieldClearDummy;
	
	private JLabel					accidentDateLabel;
	private JDateChooser 			accidentDateChooser;
	private JTextField 				accidentDateTextFieldClearDummy;
	
	private boolean					enabled;
	
//***************************************************************************
//* Class Constants                                                         *
//***************************************************************************

	public static final String  	c_IsAccident     = "AccidentPropertiesPanel.IsAccident";
	public static final String  	c_AccidentDate   = "AccidentPropertiesPanel.AccidentDate";
	public static final String  	c_AccidentNumber = "AccidentPropertiesPanel.AccidentNumber";
	
	private final static Color 		COLOR_DISABLE = new Color(238, 238, 238);
	
	private final static String 	COLUMNS =	"12dlu," +		// 1 accident selection button
												"3dlu," +		// 2
												"fill:pref," +	// 3 label
												"60dlu," +		// 4 accident number
												"3dlu," +		// 5
												"fill:pref," +	// 6 label
												"60dlu";		// 7 accident date
	
	private final static String 	ROWS =		"fill:pref";
	
//***************************************************************************
//* Constructor(s)                                                          *
//***************************************************************************

	public AccidentPanel() {
		CellConstraints l_Constraints;
		FormLayout l_Layout;
		JSpinnerDateEditor l_DateEditor;
		Color l_DefaultColor;

		this.setOpaque(false);
		this.setLayout(new BorderLayout());

		l_Constraints = new CellConstraints();

		accidentComponentPanel = new JPanel();
		accidentComponentPanel.setOpaque(false);

		l_Layout = new FormLayout(COLUMNS, ROWS);
		accidentComponentPanel.setLayout(l_Layout);

		this.accidentSelectionButton = ButtonFactory
				.createNarrowButton(PatientManagerModule
						.getIcon(PatientManagerModule.ACCIDENT_SMALL));
		this.accidentSelectionButton.setEnabled(false);
		
		accidentNumberLabel = new JLabel();
		accidentNumberLabel.setForeground(GECAMedColors.c_LabelColor);

		accidentDateLabel = new JLabel();
		accidentDateLabel.setForeground(GECAMedColors.c_LabelColor);
		
		l_DefaultColor = (Color) UIManager.getDefaults().get(
				"TextField.inactiveBackground");
		UIManager.getDefaults()
				.put("TextField.inactiveBackground", Color.WHITE);

		accidentNumberTextField = new LimitTextField(99);
		accidentNumberTextField.setHorizontalAlignment(JTextField.RIGHT);
		accidentNumberTextField.addActionListener(this);

//		l_DateEditor = new JSpinnerDateEditor();
//		l_DateEditor.setDateFormatString("d MM yyyy");
//		accidentDateChooser = new JDateChooser(new Date(), "yyyy-MM-dd", l_DateEditor);
//		accidentDateChooser.setLocale(Translatrix.getLocale());
//		accidentDateChooser.getDateEditor().setLocale(Translatrix.getLocale());
		accidentDateChooser = GECAMedGuiUtils.getDateChooser(false);
		accidentDateChooser.addPropertyChangeListener(this);

		// set clear dummy
		this.accidentDateTextFieldClearDummy = new JTextField();
		this.accidentDateTextFieldClearDummy.setEnabled(false);
		this.accidentDateTextFieldClearDummy.setBackground(COLOR_DISABLE);

		this.accidentNumberTextFieldClearDummy = new JTextField();
		this.accidentNumberTextFieldClearDummy.setEnabled(false);
		this.accidentNumberTextFieldClearDummy.setBackground(COLOR_DISABLE);

		UIManager.getDefaults().put("TextField.inactiveBackground",
				l_DefaultColor);

		this.relocalize();

		accidentComponentPanel.add(accidentSelectionButton, l_Constraints.xywh(
				1, 1, 1, 1));
		accidentComponentPanel.add(accidentNumberLabel, l_Constraints.xywh(3,
				1, 1, 1));
		accidentComponentPanel.add(accidentNumberTextField, l_Constraints.xywh(
				4, 1, 1, 1));

		accidentComponentPanel.add(accidentDateLabel, l_Constraints.xywh(6, 1,
				1, 1));
		accidentComponentPanel.add(accidentDateChooser, l_Constraints.xywh(7,
				1, 1, 1));

		accidentCheckBox = new JCheckBox(Translatrix
				.getTranslationString("AccidentPanel.title"));
		
		accidentCheckBox.setBackground(GECAMedColors.c_GECAMedBackground);
		accidentCheckBox.setOpaque(false);
		
		accidentCheckBox.addItemListener(this);

		accidentPanel = new ComponentTitledPanel(accidentCheckBox,
				accidentComponentPanel);
		accidentPanel.setOpaque(false);
		this.add(accidentPanel);

		this.setEnabled(true);
	}

	public AccidentPanel(boolean enabled) {
		super();
		this.setEnabled(enabled);
	}

	
	/**
	 * Method is part of the Relocalizable interface. The method does everything
	 * required to reflect changes of active Locale
	 */
	public void relocalize() {

//		Locale  l_Locale;
//	  	
//		l_Locale = Translatrix.getLocale ();
//		  	
//		if (l_Locale != null) 
//			 m_DateFormat = new SimpleDateFormat ("d m yyyy",l_Locale);
//		else m_DateFormat = new SimpleDateFormat ("d m yyyy");
		
		if (accidentCheckBox != null) {
			accidentCheckBox.setText(Translatrix
					.getTranslationString("AccidentPanel.title"));
		}

		if (accidentDateChooser != null) {
			accidentDateChooser.setLocale(Translatrix.getLocale());
			accidentDateChooser.getDateEditor().setLocale(
					Translatrix.getLocale());
		}

		if (accidentNumberLabel != null)
			accidentNumberLabel.setText(Translatrix
					.getTranslationString("AccidentPanel.number")
					+ " : ");

		if (accidentDateLabel != null)
			accidentDateLabel.setText(Translatrix
					.getTranslationString("AccidentPanel.date")
					+ " : ");
	}


	private void swapComponents(JComponent p_Out, JComponent p_In,
			CellConstraints p_Constraints) {
		if (p_Out.getParent() == accidentComponentPanel) {
			accidentComponentPanel.remove(p_Out);
			accidentComponentPanel.add(p_In, p_Constraints);
		}
	}

	// ---------------------------------------------------------------------------

	/**
	 * Set the accidentsPanel active and inactive.
	 * 
	 * @param enableIt
	 *            - true = active | false = inactive
	 */
	private void setEnabledState(boolean enableIt) {
		CellConstraints cellConstraints;

		cellConstraints = new CellConstraints();

		this.accidentDateLabel.setEnabled(enableIt);
		this.accidentNumberLabel.setEnabled(enableIt);

		if (enableIt) {
			
			// accidentSelectionButton enable			
			int accidentListSize = 0;

			try {				
				accidentListSize = PatientManagerModule.getPatientAccidents(
						GECAMedModule.getCurrentPatient().getId()).size();
				
			} catch (Exception e) {
			}
			if (accidentListSize > 0)	
				this.accidentSelectionButton.setEnabled(true);
			else
				this.accidentSelectionButton.setEnabled(false);
			
			
			// set date to today if it is null
			if(accidentDateChooser.getDate() == null)
				this.accidentDateChooser.setDate(new Date());
			// swapping to real components
			this.swapComponents(accidentNumberTextFieldClearDummy,
					accidentNumberTextField, cellConstraints.xywh(4, 1, 1, 1));
			this.swapComponents(accidentDateTextFieldClearDummy,
					accidentDateChooser, cellConstraints.xywh(7, 1, 1, 1));
		} else {
			this.accidentSelectionButton.setEnabled(false);
			
			// swapping to dummy components
			this.swapComponents(accidentNumberTextField,
					accidentNumberTextFieldClearDummy, cellConstraints.xywh(4,
							1, 1, 1));
			this.swapComponents(accidentDateChooser,
					accidentDateTextFieldClearDummy, cellConstraints.xywh(7, 1,
							1, 1));
			
		}
		
		this.validate();
		this.repaint();
	}
	// ---------------------------------------------------------------------------

	public void propertyChange(PropertyChangeEvent p_ChangeEvent) {
		
		if (!this.isEnabled())
			return;

		if ((p_ChangeEvent.getSource() == accidentDateChooser) && ("date".equals(p_ChangeEvent.getPropertyName()))) {
			this.firePropertyChange(c_AccidentDate, p_ChangeEvent.getOldValue(), p_ChangeEvent.getNewValue());

			if (accidentCheckBox.isSelected() && this.getAccidentNumber().length() == 0) {
				this.firePropertyChange(c_AccidentNumber, null,this.accidentNumberTextField.getText());
			}
		}
	}
	// ---------------------------------------------------------------------------

	public void actionPerformed(ActionEvent p_ChangeEvent) {
		if (!this.isEnabled())
			return;

		if (p_ChangeEvent.getSource() == accidentNumberTextField) {
			this.firePropertyChange(c_AccidentNumber, null, this
					.getAccidentNumber());
		}
	}

	// ---------------------------------------------------------------------------

	public void itemStateChanged(ItemEvent p_ChangeEvent) {
		Object l_Source;

		l_Source = p_ChangeEvent.getItemSelectable();

		if ((l_Source == accidentCheckBox) && (this.isEnabled())) {

			if (p_ChangeEvent.getStateChange() == ItemEvent.DESELECTED) {

				this.setEnabledState(false);
				this.firePropertyChange(c_IsAccident, true, false);
			} else if (p_ChangeEvent.getStateChange() == ItemEvent.SELECTED) {

				this.setEnabledState(true);
				this.firePropertyChange(c_IsAccident, false, true);
			}
		}
	}

	// ***************************************************************************
	// * Class Body *
	// ***************************************************************************

	// ---------------------------------------------------------------------------

	public void setEnabled(boolean p_EnableIt) {
		if (p_EnableIt) {
			accidentCheckBox.setEnabled(p_EnableIt);
			if (accidentCheckBox.isSelected())
				this.setEnabledState(p_EnableIt);
		} else {
			accidentCheckBox.setEnabled(p_EnableIt);
			this.setEnabledState(p_EnableIt);
		}
		enabled = p_EnableIt;
	}

	// ---------------------------------------------------------------------------

	public boolean isEnabled() {
		return enabled;
	}

	public void reset() {
		this.setAccident(false);
		this.resetAccidentDate();
		this.resetAccidentNumber();
	}

	// ---------------------------------------------------------------------------

	public boolean isAccident() {
		return accidentCheckBox.isSelected();
	}

	// ---------------------------------------------------------------------------

	public void setAccident(boolean p_IsAccident) {
		accidentCheckBox.setSelected(p_IsAccident);
		this.setEnabledState(p_IsAccident);
	}

	// ---------------------------------------------------------------------------
	/**
	 * Returns the Accident Number currently present in m_AccidentNumber text
	 * field
	 */
	// ---------------------------------------------------------------------------

	public String getAccidentNumber() {
		if(this.accidentCheckBox.isSelected())
			return this.accidentNumberTextField.getText();
		else
			return null;
	}

	
	public void setAccidentNumber(String accidentNumber) {
		if ((accidentNumber != null) && (accidentNumber.length() > 0))
			this.accidentNumberTextField.setText(accidentNumber);
		else
			this.resetAccidentNumber();
	}


	public void resetAccidentNumber() {
		this.accidentNumberTextField.setText("");

	}

	
	/**
	 * Returns the Accident Date currently selected in the Accident date
	 * chooser.
	 * 
	 * @return : returns the currently selected date if date chooser is enabled,
	 *         <b>null</b> otherwise.
	 */
	public Date getAccidentDate() {
		if(this.accidentCheckBox.isSelected())
			return this.accidentDateChooser.getDate();
		else
			return null;
	}

	
	public void setAccidentDate(Date accidentDate) {
		this.accidentDateChooser.setDate(accidentDate);
	}

	
	public void resetAccidentDate() {
		this.accidentDateChooser.setDate(new Date());
	}


	public JButton getAccidentSelectionButton() {
		return this.accidentSelectionButton;
	}

	
	public JTextField getAccidentNumberTextField() {
		return this.accidentNumberTextField;
	}

	public JDateChooser getAccidentDateChooser() {
		return this.accidentDateChooser;
	}

	public JCheckBox getAccidentCheckBox() {
		return this.accidentCheckBox;
	}
}
