/*******************************************************************************
 * 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.billing.gui.admin;

import java.awt.Color;
import java.awt.Dimension;
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.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Collection;
import java.util.Currency;
import java.util.Date;
import java.util.Iterator;

import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFormattedTextField;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.border.TitledBorder;

import lu.tudor.santec.gecamed.billing.ejb.entity.beans.Act;
import lu.tudor.santec.gecamed.billing.ejb.entity.beans.KeyValue;
import lu.tudor.santec.gecamed.billing.ejb.entity.beans.Rate;
import lu.tudor.santec.gecamed.billing.ejb.session.beans.NomenclatureBean;
import lu.tudor.santec.gecamed.billing.ejb.session.interfaces.NomenclatureInterface;
import lu.tudor.santec.gecamed.billing.utils.CurrencyFormat;
import lu.tudor.santec.gecamed.core.gui.GECAMedColors;
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.GECAMedGuiUtils;
import lu.tudor.santec.gecamed.core.gui.widgets.LimitTextField;
import lu.tudor.santec.gecamed.core.utils.ManagerFactory;
import lu.tudor.santec.i18n.Relocalizable;
import lu.tudor.santec.i18n.Translatrix;

import org.apache.log4j.Logger;

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

public class RateDialog extends JDialog implements ActionListener,
												   ItemListener,
												   PropertyChangeListener,
												   Relocalizable
	{

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

	private JPanel					m_TagPanel;
	private TitledBorder			m_TagBorder;
	private JLabel					m_CodeLabel;
	private JLabel					m_DescriptionLabel;
	private JTextField				m_Code;
	private JTextArea				m_Description;
	
	private JPanel					m_IndicatorPanel;
	private TitledBorder			m_IndicatorBorder;
	private JCheckBox				m_CAT;
	private JCheckBox				m_CAC;
	private JCheckBox				m_APCM;
	private JCheckBox				m_ACM;
	
	private JPanel					m_KeyValuePanel;
	private TitledBorder			m_KeyValueBorder;
	private JLabel					m_KeyValueLabel;
	private JComboBox<KeyValue>		m_KeyValueChooser;

	private JPanel					m_ValuePanel;
	private TitledBorder			m_ValueBorder;
	private JLabel					m_CoefficientLabel;
	private JFormattedTextField		m_Coefficient;
	private JLabel					m_DefaultAdjustmentLabel;
	private JFormattedTextField		m_DefaultAdjustmentField;
	private JLabel					m_PercentageLabel;
	private JLabel					m_ApplicabilityLabel;
	private JDateChooser			m_Applicability;
	private JLabel					m_ValueLabel;
	private JTextField				m_Value;

	private Rate					m_Rate;
	private KeyValue				m_KeyValue;

	private NumberFormat			m_CoefficientFormat;
	private CurrencyFormat			m_CurrencyFormat;
	private DecimalFormat			m_IntegerFormat;
	
	private JButton					m_UpdateButton;
	private JButton					m_CancelButton;
	private boolean					m_Canceled;
	private NomenclatureInterface	m_NomenclatureInterface;

	private TitledBorder m_InfoBorder;

	private JPanel m_InfoPanel;

	private JCheckBox m_InfoCheckBox;

	private JLabel m_InfoLabel;
	
//---------------------------------------------------------------------------
//***************************************************************************
//* Constants	                                                            *
//***************************************************************************
//---------------------------------------------------------------------------
	
	private static final long serialVersionUID = 1L;

	private final static Dimension c_PreferredSize = new Dimension (400,550);
	
	private final static int c_MaxRateChars			  = 10;
	
	private final static String c_Columns			  = "3dlu,fill:max(30dlu;pref):grow," +
														"3dlu,fill:max(35dlu;pref)," +
														"3dlu,fill:max(35dlu;pref),3dlu";
		
	private final static String c_Rows				  = "3dlu,fill:pref," +
														"3dlu,fill:pref," +
														"3dlu,fill:pref," +
														"3dlu,fill:pref," +
														"3dlu,fill:pref," +
														"3dlu,fill:pref," +
														"3dlu,fill:pref,3dlu";

	private final static String c_TagColumns      	  = "3dlu,fill:max(40dlu;pref)," +
														"3dlu,fill:max(60dlu;pref),3dlu";

	private final static String c_TagRows 	     	  = "3dlu,fill:pref," +
														"3dlu,fill:pref,3dlu";

	private final static String c_IndicatorColumns    = "3dlu,fill:max(25dlu;pref)," +
														"3dlu,fill:max(25dlu;pref)," +
														"3dlu,fill:max(25dlu;pref)," +
														"3dlu,fill:max(25dlu;pref),3dlu";

	private final static String c_IndicatorRows 	  = "3dlu,fill:pref,3dlu";

	private final static String c_KeyValueColumns     = "3dlu,fill:max(40dlu;pref)," +
														"3dlu,fill:max(60dlu;pref),3dlu";

	private final static String c_KeyValueRows 	      = "3dlu,fill:pref,3dlu";

	private final static String c_NewValueColumns     = "3dlu,fill:max(70dlu;pref)," +
														"3dlu,fill:max(25dlu;pref)," +
														"3dlu,fill:max(10dlu;pref)," +
														"3dlu,fill:max(25dlu;pref),3dlu";

	private final static String c_NewValueRows 	      = "3dlu,fill:pref," +
														"3dlu,fill:pref," +
//														"3dlu,fill:pref," +
														"3dlu,fill:pref,3dlu";

	private static final String c_Title				  = "RateDialog.Title";
	private static final String c_TagBorder			  = "RateDialog.TagBorder";
	private static final String c_CodeLabel			  = "RateDialog.CodeLabel";
	private static final String c_DescriptionLabel	  = "RateDialog.DescriptionLabel";

	private static final String c_IndicatorBorder     = "RateDialog.IndicatorBorder";
	private static final String c_CATLabel			  = "RateDialog.CATLabel";
	private static final String c_CATTip			  = "RateDialog.CATTip";
	private static final String c_CACLabel			  = "RateDialog.CACLabel";
	private static final String c_CACTip			  = "RateDialog.CACTip";
	private static final String c_APCMLabel			  = "RateDialog.APCMLabel";
	private static final String c_APCMTip			  = "RateDialog.APCMTip";
	private static final String c_ACMLabel			  = "RateDialog.ACMLabel";
	private static final String c_ACMTip			  = "RateDialog.ACMTip";
	
	private static final String c_KeyValueBorder	    = "RateDialog.KeyValueBorder";
	private static final String c_KeyValueLabel         = "RateDialog.KeyValueLabel";

	private static final String c_ValueBorder  		 		= "RateDialog.ValueBorder";
	private static final String c_CoefficientLabel   		= "RateDialog.CoefficientLabel";
	private static final String c_DefaultAdjustmentLabel	= "RateDialog.DefaultAdjustmentLabel";
	private static final String c_ApplicabilityLabel 		= "RateDialog.ApplicabilityLabel";
	private static final String c_ValueLabel     	 		= "RateDialog.ValueLabel";

//---------------------------------------------------------------------------
//***************************************************************************
//* Constructor	                                                            *
//***************************************************************************
//---------------------------------------------------------------------------

public RateDialog ()
	{
	super (MainFrame.getInstance(),Translatrix.getTranslationString(c_Title),true);
	
	CellConstraints	l_Constraints;
	FormLayout		l_Layout;	
	Color			l_DefaultColor;
	
	this.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
	
	l_Constraints  = new CellConstraints();
	
	l_DefaultColor = (Color) UIManager.getDefaults().get("TextField.inactiveBackground");   
	UIManager.getDefaults().put("TextField.inactiveBackground", Color.WHITE );

	m_CoefficientFormat = new DecimalFormat ("#0.00");
	m_CoefficientFormat.setMaximumFractionDigits(2);
	m_CoefficientFormat.setMinimumFractionDigits(2);
	m_CoefficientFormat.setMinimumIntegerDigits(1);
	m_CoefficientFormat.setGroupingUsed(false);
	
	m_IntegerFormat = new DecimalFormat("#0");
	m_IntegerFormat.setMaximumIntegerDigits(5);
	
	
	m_CurrencyFormat = new CurrencyFormat (Currency.getInstance ("EUR"));
	
	this.buildInfoPanel();
	this.buildTagPanel();
	this.buildIndicatorPanel();
	this.buildKeyValuePanel();
	this.buildValuePanel();
	
	m_UpdateButton    = new JButton ();
	m_UpdateButton.setIcon(GECAMedModule.getSmallIcon(GECAMedIconNames.OK));
	m_UpdateButton.addActionListener(this);
	
	m_CancelButton    = new JButton ();
	m_CancelButton.setIcon(GECAMedModule.getSmallIcon(GECAMedIconNames.CANCEL));
	m_CancelButton.addActionListener(this);

	this.relocalize();
	this.getContentPane().setBackground(GECAMedColors.c_GECAMedBackground);
	
	l_Layout = new FormLayout(c_Columns, c_Rows);
    this.setLayout (l_Layout);

    this.add (m_InfoPanel,  	l_Constraints.xywh(2, 2, 5, 1));
	this.add (m_TagPanel,  		l_Constraints.xywh(2, 4, 5, 1));
	this.add (m_IndicatorPanel,	l_Constraints.xywh(2, 6, 5, 1));
	this.add (m_KeyValuePanel,  l_Constraints.xywh(2, 8, 5, 1));
	this.add (m_ValuePanel,  	l_Constraints.xywh(2, 12, 5, 1));
	this.add (m_UpdateButton,  	l_Constraints.xywh(4, 14, 1, 1));
	this.add (m_CancelButton,  	l_Constraints.xywh(6, 14, 1, 1));
	
	UIManager.getDefaults().put("TextField.inactiveBackground", l_DefaultColor );	
	
	this.setSize(c_PreferredSize);
	}
	
//---------------------------------------------------------------------------
//***************************************************************************
//* Primitives		                                                        *
//***************************************************************************
//---------------------------------------------------------------------------

private JComponent	buildInfoPanel ()
{
CellConstraints	l_Constraints;
FormLayout		l_Layout;	

l_Layout      = new FormLayout("3dlu,pref:grow,3dlu,", "3dlu,pref,3dlu, pref,3dlu");
l_Constraints = new CellConstraints();

m_InfoBorder = new TitledBorder (Translatrix.getTranslationString("RateDialog.editTitle"));

m_InfoPanel = new JPanel ();
m_InfoPanel.setOpaque (false);
m_InfoPanel.setLayout(l_Layout);
m_InfoPanel.setBorder(m_InfoBorder);

m_InfoCheckBox = new JCheckBox(Translatrix.getTranslationString("RateDialog.editBox"));
m_InfoCheckBox.setOpaque(false);
m_InfoCheckBox.addActionListener(new ActionListener() {
	public void actionPerformed(ActionEvent e) {
		setEnabled(m_InfoCheckBox.isSelected());
	}
});

m_InfoLabel	 = new JLabel(Translatrix.getTranslationString("RateDialog.editLabel"));
m_InfoLabel.setForeground(Color.RED);

m_InfoPanel.add (m_InfoLabel,  				l_Constraints.xywh(2, 2, 1, 1));
m_InfoPanel.add (m_InfoCheckBox,  			l_Constraints.xywh(2, 4, 1, 1));

return m_InfoPanel;
}


private JPanel	buildTagPanel ()
	{
	CellConstraints	l_Constraints;
	FormLayout		l_Layout;	

	l_Layout      = new FormLayout(c_TagColumns, c_TagRows);
	l_Constraints = new CellConstraints();
	
	m_TagBorder = new TitledBorder ("");

	m_TagPanel = new JPanel ();
	m_TagPanel.setOpaque (false);
	m_TagPanel.setLayout(l_Layout);
	m_TagPanel.setBorder(m_TagBorder);
	
	m_CodeLabel  = new JLabel ();
	m_CodeLabel.setForeground(GECAMedColors.c_LabelColor);

	m_DescriptionLabel  = new JLabel ();
	m_DescriptionLabel.setForeground(GECAMedColors.c_LabelColor);

	m_Code = new LimitTextField(c_MaxRateChars);
	m_Code.setHorizontalAlignment(JTextField.LEFT);
	
	m_Description = new JTextArea (4,20);
	m_Description.setLineWrap(true);
	m_Description.setWrapStyleWord(true);
	
	m_TagPanel.add (m_CodeLabel,  			l_Constraints.xywh(2, 2, 1, 1));
	m_TagPanel.add (m_Code,   				l_Constraints.xywh(4, 2, 1, 1));
	m_TagPanel.add (m_DescriptionLabel,  	l_Constraints.xywh(2, 4, 1, 1));
	m_TagPanel.add (m_Description,   		l_Constraints.xywh(4, 4, 1, 1));
		
	return m_TagPanel;
	}

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

private JPanel	buildIndicatorPanel ()
	{
	CellConstraints	l_Constraints;
	FormLayout		l_Layout;	

	l_Layout      = new FormLayout(c_IndicatorColumns, c_IndicatorRows);
	l_Constraints = new CellConstraints();
	
	m_IndicatorBorder = new TitledBorder ("");

	m_IndicatorPanel = new JPanel ();
	m_IndicatorPanel.setOpaque (false);
	m_IndicatorPanel.setLayout(l_Layout);
	m_IndicatorPanel.setBorder(m_IndicatorBorder);
	
	m_CAT  = new JCheckBox ();
	m_CAT.setForeground(GECAMedColors.c_LabelColor);
	m_CAT.setBackground(GECAMedColors.c_GECAMedBackground);

	m_CAC  = new JCheckBox ();
	m_CAC.setForeground(GECAMedColors.c_LabelColor);
	m_CAC.setBackground(GECAMedColors.c_GECAMedBackground);

	m_APCM  = new JCheckBox ();
	m_APCM.setForeground(GECAMedColors.c_LabelColor);
	m_APCM.setBackground(GECAMedColors.c_GECAMedBackground);

	m_ACM  = new JCheckBox ();
	m_ACM.setForeground(GECAMedColors.c_LabelColor);
	m_ACM.setBackground(GECAMedColors.c_GECAMedBackground);
	
	m_IndicatorPanel.add (m_CAT,  l_Constraints.xywh(2, 2, 1, 1));
	m_IndicatorPanel.add (m_CAC,  l_Constraints.xywh(4, 2, 1, 1));
	m_IndicatorPanel.add (m_APCM, l_Constraints.xywh(6, 2, 1, 1));
	m_IndicatorPanel.add (m_ACM,  l_Constraints.xywh(8, 2, 1, 1));
		
	return m_IndicatorPanel;
	}

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

@SuppressWarnings("unchecked")
private JPanel	buildKeyValuePanel ()
	{
	CellConstraints	l_Constraints;
	FormLayout		l_Layout;	

	l_Layout      = new FormLayout(c_KeyValueColumns, c_KeyValueRows);
	l_Constraints = new CellConstraints();
	
	m_KeyValueBorder = new TitledBorder ("");
	
	m_KeyValuePanel = new JPanel ();
	m_KeyValuePanel.setOpaque (false);
	m_KeyValuePanel.setLayout(l_Layout);
	m_KeyValuePanel.setBorder(m_KeyValueBorder);
	
	m_KeyValueLabel  = new JLabel ();
	m_KeyValueLabel.setForeground(GECAMedColors.c_LabelColor);

	m_KeyValueChooser     = new JComboBox<KeyValue> ();
	m_KeyValueChooser.setRenderer(new KeyValueComboBoxRenderer ());
  	m_KeyValueChooser.addItemListener(this);
 	
  	m_KeyValuePanel.add (m_KeyValueLabel,  		l_Constraints.xywh(2, 2, 1, 1));
  	m_KeyValuePanel.add (m_KeyValueChooser,   	l_Constraints.xywh(4, 2, 1, 1));
	
	return m_KeyValuePanel;
	}

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

private JPanel	buildValuePanel ()
	{
	CellConstraints	l_Constraints;
	FormLayout		l_Layout;	

	l_Layout      = new FormLayout(c_NewValueColumns, c_NewValueRows);
	l_Constraints = new CellConstraints();
	
	m_ValueBorder = new TitledBorder ("");
	
	m_ValuePanel = new JPanel ();
	m_ValuePanel.setOpaque (false);
	m_ValuePanel.setLayout(l_Layout);
	m_ValuePanel.setBorder(m_ValueBorder);
	
	m_CoefficientLabel = new JLabel ();
	m_CoefficientLabel.setForeground(GECAMedColors.c_LabelColor);
	
	m_Coefficient  = new JFormattedTextField (m_CoefficientFormat);
	m_Coefficient.addPropertyChangeListener(this);
	
	m_ValueLabel = new JLabel ();
	m_ValueLabel.setForeground(GECAMedColors.c_LabelColor);
	
	m_Value   = new JTextField ();
	m_Value.setEditable(false);
	
	m_DefaultAdjustmentLabel = new JLabel();
	m_DefaultAdjustmentLabel.setForeground(GECAMedColors.c_LabelColor);
	
	m_DefaultAdjustmentField = new JFormattedTextField(m_IntegerFormat);
	m_DefaultAdjustmentField.addPropertyChangeListener(this);
	
	m_PercentageLabel = new JLabel("%");
	m_PercentageLabel.setForeground(GECAMedColors.c_LabelColor);
	
	m_ApplicabilityLabel = new JLabel ();
	m_ApplicabilityLabel.setForeground(GECAMedColors.c_LabelColor);
	
	m_Applicability = GECAMedGuiUtils.getDateChooser(false);
	m_Applicability.setDate(new Date ());
	m_Applicability.addPropertyChangeListener(this);
	m_Applicability.getDateEditor().addPropertyChangeListener(this);

	m_ValuePanel.add (m_CoefficientLabel,		l_Constraints.xywh(2, 2, 1, 1));
	m_ValuePanel.add (m_Coefficient,			l_Constraints.xywh(4, 2, 1, 1));
	m_ValuePanel.add (m_ValueLabel,				l_Constraints.xywh(6, 2, 1, 1));
	m_ValuePanel.add (m_Value,					l_Constraints.xywh(8, 2, 1, 1));
	m_ValuePanel.add (m_DefaultAdjustmentLabel,	l_Constraints.xywh(2, 4, 1, 1));
	m_ValuePanel.add (m_DefaultAdjustmentField,	l_Constraints.xywh(4, 4, 3, 1));
	m_ValuePanel.add (m_PercentageLabel,		l_Constraints.xywh(8, 4, 1, 1));
	m_ValuePanel.add (m_ApplicabilityLabel,		l_Constraints.xywh(2, 6, 1, 1));
	m_ValuePanel.add (m_Applicability,			l_Constraints.xywh(4, 6, 5, 1));

	return m_ValuePanel;
	}

private void selectFirstEditableKeyValue ()
	{
	KeyValue	l_KeyValue;
	int			l_KeyValueCount;
	int			l_Position	= 0;
	boolean		l_Found 	= false;	
	
	l_KeyValueCount = m_KeyValueChooser.getItemCount();
	
	while ((l_Position < l_KeyValueCount) && (!l_Found))
		{
		l_KeyValue = (KeyValue) m_KeyValueChooser.getItemAt(l_Position);	
		l_Found = l_KeyValue.getEditable();	
		if (!l_Found) l_Position++;	
		}
	
	if (l_Found) m_KeyValueChooser.setSelectedIndex(l_Position);
	}

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

private void populateKeyValues (Collection <KeyValue> p_KeyValues)
	{
	Iterator <KeyValue>	l_KeyValueIterator;
	
	if (p_KeyValues == null) return;
	
	m_KeyValueChooser.removeItemListener (this);
	m_KeyValueChooser.removeAllItems();
	l_KeyValueIterator = p_KeyValues.iterator();
	while (l_KeyValueIterator.hasNext())
		{
		m_KeyValueChooser.addItem (l_KeyValueIterator.next());
		}
	m_KeyValueChooser.setSelectedIndex(0);
	m_KeyValueChooser.addItemListener (this);
	}

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

private void updateDialogFromRate (Rate p_Rate)
	{	

	m_Code.setEditable(true);
	
	if (p_Rate == null) return;
	
	m_Code.setEditable(! p_Rate.isPersistent());
	m_Code.setText((p_Rate.getCode() != null)?p_Rate.getCode():"");
	m_Description.setText((p_Rate.getLabel() != null)?p_Rate.getLabel():"");
	
	m_CAT.setSelected(p_Rate.getCAT());
	m_CAC.setSelected(p_Rate.getCAC());
	m_APCM.setSelected(p_Rate.getAPCM());
	m_ACM.setSelected(p_Rate.getACM());
	
	if (p_Rate.getKeyType() != null)
		{
		for (int i = 0; i < m_KeyValueChooser.getItemCount(); i++) {
			KeyValue val = m_KeyValueChooser.getItemAt(i);
			if (val.getKeyType().equals(p_Rate.getKeyType())) {
				m_KeyValueChooser.setSelectedIndex(i);	
				break;
			}
		}
		m_KeyValue = (m_KeyValueChooser.getSelectedItem() != null) ? (KeyValue)m_KeyValueChooser.getSelectedItem():null;
		this.setEnabled(m_KeyValue.getEditable());
		}
	else 
		{
		this.selectFirstEditableKeyValue();
		m_KeyValue = (m_KeyValueChooser.getSelectedItem() != null) ? (KeyValue)m_KeyValueChooser.getSelectedItem():null;
		p_Rate.setKeyType(m_KeyValue.getKeyType());
		}	
		
	m_Coefficient.setValue ((p_Rate.getCoefficient()!=null)?p_Rate.getCoefficient():Double.valueOf(0d));
	m_Applicability.setDate (p_Rate.getApplicability());
	m_DefaultAdjustmentField.setValue(p_Rate.getDefaultAdjustment() != null ? p_Rate.getDefaultAdjustment().intValue() : 100);

	this.updateMonetaryFields(p_Rate);
	}

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

private Rate updateRateFromDialog (Rate p_Rate)
	{
	if (p_Rate == null) return p_Rate;
	
	p_Rate.setCode  (m_Code.getText().toUpperCase());
	p_Rate.setLabel (m_Description.getText());
	p_Rate.setCAT   (m_CAT.isSelected());
	p_Rate.setCAC   (m_CAC.isSelected());
	p_Rate.setAPCM  (m_APCM.isSelected());
	p_Rate.setACM   (m_ACM.isSelected());
	
	p_Rate.setKeyType( ((KeyValue)m_KeyValueChooser.getSelectedItem()).getKeyType());
	p_Rate.setApplicability (m_Applicability.getDate());
	p_Rate.setCoefficient(this.getDoubleValueOf(m_Coefficient.getText()));
	p_Rate.setDefaultAdjustment(m_DefaultAdjustmentField.getValue() != null 
			? ((Number)m_DefaultAdjustmentField.getValue()).intValue() : Act.DEFAULT_ADJUSTMENT);
	
	return p_Rate;
	}

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

private NomenclatureInterface getNomenclatureInterface ()
	{
	if (m_NomenclatureInterface != null) return m_NomenclatureInterface;

	try {
		m_NomenclatureInterface = (NomenclatureInterface) ManagerFactory.getRemote(NomenclatureBean.class);
		} 
	catch (Exception p_Exception) 
		{
		m_Logger.warn(p_Exception.getLocalizedMessage());
		}

	return m_NomenclatureInterface;
	}

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

private void updateMonetaryFields (Rate p_Rate)
	{
	
	KeyValue l_KeyValue = null;
	
	if (p_Rate == null) return;
	
	if (p_Rate.getApplicability() == null) p_Rate.setApplicability(new Date());
	
	try {
		l_KeyValue = getNomenclatureInterface().getKeyValueByTypeAndPerformedDate(p_Rate.getKeyType(), p_Rate.getApplicability());		
	} catch (Exception e) {
		m_Logger.error("error initializing Act", e);
	}

	m_Value.setText(m_CurrencyFormat.format(p_Rate.monetize(l_KeyValue)));	
	}

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

private double getDoubleValueOf (String p_Text)
	{
	Number	l_Value;
	
	try	{
		l_Value = m_CoefficientFormat.parse (p_Text);
		}
	catch (ParseException p_Exception)
		{
		l_Value = 0d;
		}

	return l_Value.doubleValue();
	}
//---------------------------------------------------------------------------
//***************************************************************************
//* Class Body	                                                            *
//***************************************************************************
//---------------------------------------------------------------------------

public void setKeyValues (Collection <KeyValue> p_KeyValues)
	{
	if (p_KeyValues != null)
		{
		this.populateKeyValues(p_KeyValues);
		}
	}

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

public void setRate (Rate p_Rate)
	{
	if (p_Rate == null) return;
	
	m_Rate = p_Rate;
	this.updateDialogFromRate(m_Rate);	
	
	m_InfoCheckBox.setEnabled(p_Rate.isPersistent());
	m_InfoLabel.setEnabled(p_Rate.isPersistent());
	setEnabled(! p_Rate.isPersistent());
	
	}

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

public Rate getRate ()
	{
	if (m_Rate != null)
		{
		m_Rate = this.updateRateFromDialog (m_Rate);	
		}
	return 	m_Rate;
	}

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

public void setEnabled (boolean p_EnableIt)
	{
	if (m_Rate!= null) {
		m_Code.setEditable(! m_Rate.isPersistent());
	} else {
		m_Code.setEditable(p_EnableIt);		
	}
	m_Description.setEditable(p_EnableIt);
	m_CAT.setEnabled(p_EnableIt);
	m_CAC.setEnabled(p_EnableIt);
	m_APCM.setEnabled(p_EnableIt);
	m_ACM.setEnabled(p_EnableIt);
	m_KeyValueChooser.setEnabled(p_EnableIt);
	m_Applicability.setEnabled (p_EnableIt);
	m_Coefficient.setEditable(p_EnableIt);
	m_DefaultAdjustmentField.setEditable(p_EnableIt);
	m_UpdateButton.setEnabled(p_EnableIt);
	}
//---------------------------------------------------------------------------

public void relocalize()
	{		
	this.setTitle(Translatrix.getTranslationString(c_Title));

	if (m_TagBorder != null)
		m_TagBorder.setTitle (Translatrix.getTranslationString(c_TagBorder));
		
	if (m_CodeLabel != null)
		m_CodeLabel.setText (Translatrix.getTranslationString(c_CodeLabel));

	if (m_DescriptionLabel != null)
		m_DescriptionLabel.setText (Translatrix.getTranslationString(c_DescriptionLabel));
	
	if (m_IndicatorBorder != null)
		m_IndicatorBorder.setTitle (Translatrix.getTranslationString(c_IndicatorBorder));
	
	if (m_CAT != null)
		{
		m_CAT.setText(Translatrix.getTranslationString(c_CATLabel));
		m_CAT.setToolTipText(Translatrix.getTranslationString(c_CATTip));
		}
	
	if (m_CAC != null)
		{
		m_CAC.setText(Translatrix.getTranslationString(c_CACLabel));
		m_CAC.setToolTipText(Translatrix.getTranslationString(c_CACTip));
		}
	
	if (m_APCM != null)
		{
		m_APCM.setText(Translatrix.getTranslationString(c_APCMLabel));
		m_APCM.setToolTipText(Translatrix.getTranslationString(c_APCMTip));
		}
	
	if (m_ACM != null)
		{
		m_ACM.setText(Translatrix.getTranslationString(c_ACMLabel));
		m_ACM.setToolTipText(Translatrix.getTranslationString(c_ACMTip));
		}
	
	if (m_KeyValueBorder != null)
		m_KeyValueBorder.setTitle (Translatrix.getTranslationString(c_KeyValueBorder));
	
	if (m_KeyValueLabel != null)
		m_KeyValueLabel.setText (Translatrix.getTranslationString(c_KeyValueLabel));

	if (m_ValueBorder != null)
		m_ValueBorder.setTitle (Translatrix.getTranslationString(c_ValueBorder));
	
	if (m_ApplicabilityLabel != null)
		m_ApplicabilityLabel.setText (Translatrix.getTranslationString(c_ApplicabilityLabel));
	
	if (m_Applicability != null) 
		{
		m_Applicability.setLocale (Translatrix.getLocale());
		m_Applicability.setDateFormatString("d MMMM yyyy");   
		m_Applicability.getDateEditor().setLocale (Translatrix.getLocale());
		}

	if (m_CoefficientLabel != null)
		m_CoefficientLabel.setText (Translatrix.getTranslationString(c_CoefficientLabel));
	
	if (m_ValueLabel != null)
		m_ValueLabel.setText (Translatrix.getTranslationString(c_ValueLabel));
	
	if (m_DefaultAdjustmentLabel != null)
		m_DefaultAdjustmentLabel.setText(Translatrix._(c_DefaultAdjustmentLabel));
	
	if (m_UpdateButton != null)
		m_UpdateButton.setText (Translatrix.getTranslationString("core.save"));
	
	if (m_CancelButton != null)
		m_CancelButton.setText(Translatrix.getTranslationString("core.cancel"));
	}

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

public void actionPerformed (ActionEvent p_ActionEvent)
	{
	if (p_ActionEvent.getSource() == m_CancelButton)
		{
		this.setVisible (false);
		m_Canceled = true;
		}
	else if (p_ActionEvent.getSource() == m_UpdateButton)
		{
		m_Canceled = false;
		this.setVisible (false);
		}
	}

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

public void itemStateChanged (ItemEvent p_ChangeEvent)
	{
	if (p_ChangeEvent.getItemSelectable().equals(m_KeyValueChooser))
		{
		m_KeyValue = (KeyValue) p_ChangeEvent.getItem();	
		if (m_Rate != null)
			{
			m_Rate.setKeyType( ((KeyValue)m_KeyValueChooser.getSelectedItem()).getKeyType());
			m_UpdateButton.setEnabled(m_KeyValue.getEditable());
			this.updateMonetaryFields(m_Rate);
			}
		}
		
	}

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

public void propertyChange (PropertyChangeEvent p_ChangeEvent)
	{
	if (!this.isVisible()) return;
	
	if (m_Rate == null) return;
	
	if ((p_ChangeEvent.getSource().equals(m_Applicability)) 
			&& ("date".equals(p_ChangeEvent.getPropertyName())))
		{
		m_Rate.setApplicability (m_Applicability.getDate());
		this.updateMonetaryFields(m_Rate);	
		}
	else if (p_ChangeEvent.getSource().equals(m_Coefficient))
		{
		m_Rate.setCoefficient(this.getDoubleValueOf(m_Coefficient.getText()));
		this.updateMonetaryFields(m_Rate);	
		}
	else if (p_ChangeEvent.getSource().equals(m_DefaultAdjustmentField))
		{
		m_Rate.setDefaultAdjustment(m_DefaultAdjustmentField.getValue() != null 
				? ((Number)m_DefaultAdjustmentField.getValue()).intValue() : Act.DEFAULT_ADJUSTMENT);
		this.updateMonetaryFields(m_Rate);
		}
	}

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

public boolean wasCanceled ()
	{
	return m_Canceled;	
	}

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


//***************************************************************************
//* End of Class                                                             *
//***************************************************************************
//---------------------------------------------------------------------------
	}
