/*******************************************************************************
 * 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.Component;
import java.awt.Font;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Date;
import java.util.Locale;

import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.SwingConstants;
import javax.swing.tree.TreePath;

import lu.tudor.santec.gecamed.billing.ejb.entity.beans.Rate;
import lu.tudor.santec.gecamed.billing.gui.BillingModule;
import lu.tudor.santec.gecamed.core.gui.utils.GECAMedGuiUtils;
import lu.tudor.santec.gecamed.core.gui.widgets.GenericRenderer;
import lu.tudor.santec.i18n.Relocalizable;
import lu.tudor.santec.i18n.Translatrix;

import org.jdesktop.swingx.JXTreeTable;

//***************************************************************************
//* Class Definition and Members                                            *
//***************************************************************************

public class RateRenderer extends GenericRenderer implements Relocalizable 
	{
	private JTextArea				m_Label;
	private ImageIcon				m_CheckedIcon;   
	private ImageIcon				m_WarningIcon;   

	private String              	m_CATTip;
	private String              	m_CACTip;
	private String              	m_APCMTip;
	private String              	m_ACMTip;
	
	private NumberFormat 			m_CoefficientFormat;
	private DateFormat				m_DateFormat;
	private JXTreeTable 			m_Table;
	
//***************************************************************************
//* Class Constants                                                         *
//***************************************************************************

	private static final long serialVersionUID = 1L;
 	
	private static final int   c_Gap   = 2;

//***************************************************************************
//* Constructor(s)                                                          *
//***************************************************************************
   
public RateRenderer (JXTreeTable table)
	{
    super();
     
	m_Table = table;
    m_Label = new JTextArea ();
    m_Label.setLineWrap(true);
    m_Label.setWrapStyleWord(true);
    m_Label.setBorder(BorderFactory.createEmptyBorder (c_Gap,c_Gap,c_Gap,c_Gap));
    m_Label.setFont (new Font (getFont().getName(), Font.PLAIN, 10));	
      
    m_CheckedIcon = BillingModule.getIconResource ("checked.png");
    m_WarningIcon = BillingModule.getIconResource ("warning.png");
       	
  	m_CoefficientFormat = new DecimalFormat ("#0.00");
  	m_CoefficientFormat.setMaximumFractionDigits(2);
  	m_CoefficientFormat.setMinimumFractionDigits(2);
  	m_CoefficientFormat.setMinimumIntegerDigits(1);
  	
  	m_Today = new Date ();
  	
  	this.relocalize();       
    }

//***************************************************************************
//* Primitives                                       						*
//***************************************************************************

//---------------------------------------------------------------------------
//***************************************************************************
//* Class Body                                                              *
//***************************************************************************
     
//---------------------------------------------------------------------------
/**
 * Method is part of the Relocalizable interface. The method does everything
 * required to reflect changes of active Locale
 */
//---------------------------------------------------------------------------

public void relocalize() 
	{
	Locale  l_Locale;
	 
	super.relocalize();
		
	m_CATTip		= Translatrix.getTranslationString ("RateRenderer.CATTip");
    m_CACTip		= Translatrix.getTranslationString ("RateRenderer.CACTip");
    m_APCMTip		= Translatrix.getTranslationString ("RateRenderer.APCMTip");
    m_ACMTip		= Translatrix.getTranslationString ("RateRenderer.ACMTip");
	
	l_Locale = Translatrix.getLocale ();

	m_DateFormat = GECAMedGuiUtils.getDateFormat(false);

	}

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

public Component getTableCellRendererComponent (JTable p_Table, Object p_Value,
        										 boolean p_IsSelected, 
        										 boolean p_HasFocus, 
        										 int p_Row, int p_Column) 
	{
	Component			l_Component;
	JLabel      		l_Label;
	String				l_Abstract;
	int					l_Column;
	Rate				l_Rate;
		
	l_Label = (JLabel) super.getTableCellRendererComponent(p_Table, p_Value, 
													           p_IsSelected, p_HasFocus, 
													           p_Row, p_Column);
		
	l_Component = l_Label;
	
	if ((p_Value != null) && (l_Label != null)) 
		{
		l_Column = this.modelColumn(p_Table, p_Column);	
		
		TreePath l_SelectionPath = m_Table.getPathForRow (p_Row);
		RateTreeNode l_Node = (RateTreeNode) l_SelectionPath.getLastPathComponent();
		l_Rate = l_Node.getRate();
		
		switch (l_Column)
			{
			case RateTreeTableModel.c_LabelColumn :
				
			   l_Abstract = ((String)p_Value);
			   if (l_Abstract.length() > 64) 
				   {
				   l_Abstract = l_Abstract.substring(0, 64);
				   l_Abstract += "...";	
				   }
				   
			   m_Label.setText(l_Abstract);
			   m_Label.setToolTipText((String)p_Value);
			   m_Label.setSize(p_Table.getColumnModel().getColumn(p_Column).getWidth(),getPreferredSize().height);
			   m_Label.setBackground(l_Label.getBackground());
			   
//			   if (p_Table.getRowHeight(p_Row) < m_Label.getPreferredSize().height) 
//				   {
//				   p_Table.setRowHeight(m_Label.getPreferredSize().height);
//				   }
			   
			   l_Component = m_Label;
			break;
			   
			
			case RateTreeTableModel.c_CATColumn :
	
				if ((p_Value instanceof Boolean) && (Boolean)p_Value) 
					{
					l_Label.setIcon (m_CheckedIcon);
					l_Label.setToolTipText (m_CATTip);		  
					}
				else l_Label.setIcon (null);
				break;
			
			case RateTreeTableModel.c_CACColumn :
			
				if ((p_Value instanceof Boolean) && (Boolean)p_Value)  
					{
					l_Label.setIcon (m_CheckedIcon);
					l_Label.setToolTipText (m_CACTip);		  
					}
				else l_Label.setIcon (null);
				break;

			case RateTreeTableModel.c_APCMColumn :
			
				if ((p_Value instanceof Boolean) && (Boolean)p_Value)  
					{
					l_Label.setIcon (m_WarningIcon);
					l_Label.setToolTipText (m_APCMTip);		  
					}
				else l_Label.setIcon (null);
				break;

			case RateTreeTableModel.c_ACMColumn :
			
				if ((p_Value instanceof Boolean) && (Boolean)p_Value) 
					{
					l_Label.setIcon (m_WarningIcon);
					l_Label.setToolTipText (m_ACMTip);		  
					}
				else l_Label.setIcon (null);
				break;

			case RateTreeTableModel.c_ApplicabilityColumn :
				
				if (p_Value instanceof Date) 
					{
					l_Label.setText (m_DateFormat.format(p_Value));
					l_Label.setHorizontalAlignment(SwingConstants.CENTER);
					}
				break;
			
			case RateTreeTableModel.c_CoefficientColumn :
				
				if (p_Value instanceof Double) 
					{
					l_Label.setText (m_CoefficientFormat.format(p_Value));
					l_Label.setHorizontalAlignment(SwingConstants.RIGHT);
					
					if (l_Rate != null) {
						try {
							if (l_Rate.getApplicability() != null && l_Rate.getApplicability().after(m_Today)) {
								l_Label.setForeground(Color.ORANGE);
							} else if ( isNodeOutdated(l_Node) ) {
								l_Label.setForeground(Color.GRAY);
							} else {
								l_Label.setForeground(Color.GREEN.darker());
							}						
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
					
					}
				break;
			
			case RateTreeTableModel.c_AmountColumn :
			
				if (p_Value instanceof Double) 
					{
					l_Label.setText (this.formatAmount((Double)p_Value));
					l_Label.setHorizontalAlignment(SwingConstants.RIGHT);
					
					if (l_Rate != null) {
						try {
							if (l_Rate.getApplicability() != null && l_Rate.getApplicability().after(m_Today)) {
								l_Label.setForeground(Color.ORANGE);
							} else if ( isNodeOutdated(l_Node) ) {
								l_Label.setForeground(Color.GRAY);
							} else {
								l_Label.setForeground(Color.GREEN.darker());
							}						
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
					
					}
				break;
		
			default:
		
				l_Label.setText (p_Value.toString());
				break;
			}
		}
	
	return l_Component;
	}


private boolean isNodeOutdated(RateTreeNode l_Node) {
	RateTreeNode l_Parent = (RateTreeNode) l_Node.getParent();
	if (l_Parent.getRate() != null ) {
		Date fromDate = l_Parent.getRate().getApplicability();
		if (fromDate.before(m_Today))
			return true;
	}
	
	for (int i = 0; i < l_Parent.getChildCount(); i++) {
		RateTreeNode l_OtherNode = (RateTreeNode) l_Parent.getChildAt(i);
		if (l_OtherNode == null || l_OtherNode.getRate() == null ) {
			continue;
		}
		
		Date otherFromDate = l_OtherNode.getRate().getApplicability();
		
		if (! l_OtherNode.getRate().getCode().equals(l_Node.getRate().getCode())) {
			continue;
		}
		
		if (otherFromDate.before(m_Today)) {
			if ( ! l_OtherNode.equals(l_Node) ) {
				return true;
			} else {
				return false;
			}
		} else {
			return false;
		}
	}
	return false;
}

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