/*******************************************************************************
 * 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.invoice;

import java.awt.Color;
import java.awt.Component;
import java.text.DateFormat;
import java.text.NumberFormat;
import java.util.Calendar;
import java.util.Currency;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;

import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableCellRenderer;

import lu.tudor.santec.gecamed.billing.ejb.entity.beans.Invoice;
import lu.tudor.santec.gecamed.billing.gui.BillingModule;
import lu.tudor.santec.gecamed.billing.utils.InvoiceWorkflow;
import lu.tudor.santec.gecamed.core.gui.GECAMedColors;
import lu.tudor.santec.gecamed.core.gui.utils.GECAMedGuiUtils;
import lu.tudor.santec.gecamed.core.gui.utils.TableSorter;
import lu.tudor.santec.gecamed.core.gui.widgets.searchtableheader.SearchTableHeader;
import lu.tudor.santec.gecamed.office.ejb.entity.beans.Physician;
import lu.tudor.santec.i18n.Relocalizable;
import lu.tudor.santec.i18n.Translatrix;

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

public class InvoiceRenderer extends DefaultTableCellRenderer implements Relocalizable 
	{
	private JLabel              	m_Label;
	private DateFormat    			m_DateFormat;
	
	private NumberFormat			m_CurrencyFormat;
	private InvoiceListModel		m_TableModel;
	private	TableSorter				m_InvoiceSorter;
	private Invoice					m_Invoice;
	private boolean					m_IsAlarm;
	
	private SearchTableHeader		m_SearchHeader;
	
//***************************************************************************
//* Class Constants                                                         *
//***************************************************************************

	private static final long serialVersionUID = 1L;
 	
	public static final ImageIcon	m_OpenState     = BillingModule.getIconResource("invoice_open_state.png");
	public static final ImageIcon	m_VerifiedState = BillingModule.getIconResource("invoice_verified_state.png");
	public static final ImageIcon	m_ClosedState   = BillingModule.getIconResource("invoice_closed_state.png");
	public static final ImageIcon	m_PrintedState  = BillingModule.getIconResource("invoice_printed_state.png");
	public static final ImageIcon	m_ReminderState = BillingModule.getIconResource("invoice_reminded_state.png");
	public static final ImageIcon	m_PaidState     = BillingModule.getIconResource("invoice_paid_state.png");
	public static final ImageIcon	m_PartPaidState = BillingModule.getIconResource("invoice_partpaid_state.png");
	public static final ImageIcon	m_CanceledState = BillingModule.getIconResource("invoice_canceled_state.png");
	
//***************************************************************************
//* Constructor(s)                                                          *
//***************************************************************************
   
public InvoiceRenderer ()
      {
     super();

     GregorianCalendar	l_EarliestToday;
      
     m_Label = new JLabel ();
     m_Label.setOpaque(true);
     m_Label.setHorizontalAlignment (SwingConstants.CENTER);
       
     m_TableModel 		= null;
     m_Invoice    		= null;
     m_SearchHeader 	= null;
      
     l_EarliestToday = new GregorianCalendar();
     l_EarliestToday.setTime (new Date ());
     l_EarliestToday.set(Calendar.HOUR_OF_DAY,0);
     l_EarliestToday.set(Calendar.MINUTE,0);
     l_EarliestToday.set(Calendar.SECOND,0);
     l_EarliestToday.set(Calendar.MILLISECOND,0);
	
     
     this.relocalize();       
     }

//***************************************************************************
//* Class Primitives		                                                  *
//***************************************************************************

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

private String getPhysicianShortName (Physician p_Physician)
	{
	String l_ShortName = "";
	
	if ((p_Physician != null) 
			&& (p_Physician.getFirstName() != null) 
			&& (p_Physician.getFirstName().length() > 0))
		{
		l_ShortName = (p_Physician.getFirstName().substring(0,1).toUpperCase()) +
					 ". " + p_Physician.getName();
		}
	
	return l_ShortName;
	}

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

public static void setStateImageAndToolTip (Integer p_InvoiceState, JLabel l_Label, Double balance)
	{
	String	l_InvoiceStateName;
	
	l_InvoiceStateName = InvoiceWorkflow.getInvoiceStateName(p_InvoiceState);
	
	switch (p_InvoiceState)
		{
		case InvoiceWorkflow.c_NewState:
		case InvoiceWorkflow.c_OpenState: 		l_Label.setIcon(m_OpenState);
												break;
		case InvoiceWorkflow.c_VerifiedState: 	l_Label.setIcon(m_VerifiedState);
												break;
		case InvoiceWorkflow.c_ClosedState: 	l_Label.setIcon(m_ClosedState);
												break;
		case InvoiceWorkflow.c_PrintedState:	l_Label.setIcon(m_PrintedState);
												break;	
		case InvoiceWorkflow.c_RemindedState:	l_Label.setIcon(m_ReminderState);
												break;
		case InvoiceWorkflow.c_PaidState:
												if (balance == null || balance == 0) {
													l_Label.setIcon(m_PaidState);	
												} else {
													l_Label.setIcon(m_PartPaidState);													
												}
												break;
		case InvoiceWorkflow.c_CanceledState:	l_Label.setIcon(m_CanceledState);
												break;				
		}

	l_Label.setToolTipText (Translatrix.getTranslationString("InvoiceRenderer." + l_InvoiceStateName));	
	}

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

private String getLabelText (Date p_Date)
	{
	if (p_Date.equals (InvoiceListModel.c_Epoch))
		 return "";
	else return m_DateFormat.format (p_Date);
	}

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

private int modelRow (int p_ViewRow)
	{
	int	l_ModelRow;
	
	l_ModelRow = p_ViewRow;
	
	if ((m_InvoiceSorter != null) && m_InvoiceSorter.isSorting())
		{
		l_ModelRow = m_InvoiceSorter.modelIndex(l_ModelRow);
		}
	
	return l_ModelRow;
	}

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

public int modelColumn (JTable p_Table, int p_ViewColumn) 
	{
    if (p_Table == null) return -1;
	
	if (p_ViewColumn >= p_Table.getColumnCount()) return -1;
  
    return p_Table.getColumnModel().getColumn(p_ViewColumn).getModelIndex();
	}

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

public void setSearchHeader (SearchTableHeader p_SearchHeader)
	{
	m_SearchHeader = p_SearchHeader;
	}

//---------------------------------------------------------------------------
/**
 * 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 MMMM yyyy",l_Locale);
//    else m_DateFormat = new SimpleDateFormat ("d MMMM yyyy");   
    m_DateFormat = GECAMedGuiUtils.getDateFormat(false);
    
 //   m_CurrencyFormat = NumberFormat.getCurrencyInstance (Translatrix.getLocale());
    m_CurrencyFormat = NumberFormat.getCurrencyInstance (Locale.FRANCE);
    m_CurrencyFormat.setCurrency(Currency.getInstance ("EUR"));
	}

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

public Component getTableCellRendererComponent (JTable p_Table, Object p_Value,
        										 boolean p_IsSelected, 
        										 boolean p_HasFocus, 
        										 int p_Row, int p_Column) 
	{
	Color			l_Background;
	Physician		l_Physician;
	int				l_Row = -1;
	int				l_Column = -1;
	
	if ((p_Table != null) && (m_TableModel == null)) 
		{
		m_InvoiceSorter = (TableSorter) p_Table.getModel();
		m_TableModel 	= (InvoiceListModel) m_InvoiceSorter.getTableModel();
		}
	
	if (m_TableModel != null)  //&& (p_Row != m_LastRow))
		{
		l_Row = this.modelRow (p_Row);
		m_Invoice = m_TableModel.getInvoiceAt (l_Row);
		
		if (m_Invoice != null) m_IsAlarm = m_Invoice.isExpired();
		}
	
	m_Label.setIcon (null);
	m_Label.setToolTipText (null);
	m_Label.setText ("");
	m_Label.setHorizontalAlignment (SwingConstants.CENTER);
	m_Label.setForeground (Color.BLACK);

	if ((p_Value != null) && (m_Invoice != null)) 
		{
		l_Column = this.modelColumn(p_Table, p_Column);
		
		switch (l_Column)
			{
			case InvoiceListModel.c_StatusColumn :
				
				setStateImageAndToolTip(m_Invoice.getState(), m_Label, m_Invoice.getBalance());
				break;
				
			case InvoiceListModel.c_HospitalisationClassColumn :
				m_Label.setText ((String)p_Value);
				break;
				
			case InvoiceListModel.c_InvoiceNumberColumn :
				
				m_Label.setText ((String)p_Value);
				m_Label.setToolTipText(m_Invoice.formatInvoiceNumber(false, true));
				break;
				
			case InvoiceListModel.c_InvoiceDateColumn :	
				
				m_Label.setText(this.getLabelText((Date)p_Value));
				break;
				
			case InvoiceListModel.c_DueDateColumn :
				
				if (m_IsAlarm) m_Label.setForeground(GECAMedColors.c_InvalidFieldForeground);			
				m_Label.setText(this.getLabelText((Date)p_Value));
				break;
				
			case InvoiceListModel.c_PhysicianColumn :
				
				l_Physician = (Physician)p_Value;
				m_Label.setText (getPhysicianShortName(l_Physician));
				m_Label.setToolTipText(l_Physician.getUcmCode());
				break;
			
			case InvoiceListModel.c_SettlementDateColumn :
				
				if (m_Invoice.getSettlement() != null)
					{
					m_Label.setText (m_DateFormat.format ((Date)p_Value));
					}
				break;
				
			case InvoiceListModel.c_ReminderColumn :
				
				if (m_Invoice.getNumberOfReminders().intValue() > 0)
					{
					if (m_Invoice.getNumberOfReminders().intValue() <= 2)
						{
						m_Label.setText(m_Invoice.getNumberOfReminders().toString());
						}
					else
						{
						m_Label.setText(Translatrix.getTranslationString("InvoiceRenderer.DemandForPayment"));
						}
					}
				break;
				
			case InvoiceListModel.c_ReminderDateColumn :
				
				if (m_Invoice.getNumberOfReminders().intValue() > 0)
					{
					m_Label.setText(this.getLabelText((Date)p_Value));
					}
				break;
				
			case InvoiceListModel.c_AccidentDateColumn :
				
				if (m_Invoice.isAccident())
					{
					m_Label.setText(this.getLabelText((Date)p_Value));
					}
				break;
				
			case InvoiceListModel.c_AmountColumn:
			case InvoiceListModel.c_PaymentColumn:
			case InvoiceListModel.c_DeductionColumn:
			case InvoiceListModel.c_BalanceColumn:
				
				m_Label.setHorizontalAlignment (SwingConstants.RIGHT);
				m_Label.setText (m_CurrencyFormat.format(((Double)p_Value)));
				break;
			
			default:
				
				m_Label.setText (p_Value.toString());
				break;		
			}
		}

	if (p_Table != null) m_Label.setEnabled (p_Table.isEnabled());

	if (!m_IsAlarm)
		{
		if ((m_SearchHeader != null) && (m_SearchHeader.isSearchColumn(l_Column)))
			{
			l_Background = ( p_Row % 2 == 0) ? GECAMedColors.c_OddLineSearchBackground : 
				 							   GECAMedColors.c_EvenLineSearchBackground;
			}
		else
			{
			l_Background = ( p_Row % 2 == 0) ? GECAMedColors.c_OddLineBackground : 
										 	   GECAMedColors.c_EvenLineBackground;
			}
		}
	else
		{
		if ((m_SearchHeader != null) && (m_SearchHeader.isSearchColumn(l_Column)))
			{
			l_Background = ( p_Row % 2 == 0) ? GECAMedColors.c_RedOddLineSearchBackground : 
			 						     	   GECAMedColors.c_RedEvenLineSearchBackground;
			}
		else
			{
			l_Background = ( p_Row % 2 == 0) ? GECAMedColors.c_RedOddLineBackground : 
		     	   							   GECAMedColors.c_RedEvenLineBackground;
			}
		}
	
	if ((p_Table != null) && (p_IsSelected)) 
		{
		m_Label.setBackground(p_Table.getSelectionBackground());
		} 
	else 
		{
		m_Label.setBackground(l_Background);
		}

return m_Label;
}

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