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

/*
 * InvoiceListBox.java
 *
 * Created on April 3, 2006
 */

 import java.awt.Component;
import java.awt.event.KeyListener;
import java.awt.event.MouseListener;
import java.util.Collection;
import java.util.Vector;

import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableColumnModel;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;

import lu.tudor.santec.gecamed.billing.ejb.entity.beans.Invoice;
import lu.tudor.santec.gecamed.core.gui.utils.TableSorter;
import lu.tudor.santec.i18n.Relocalizable;

//***************************************************************************
//* Class Definition                                                        *
//***************************************************************************

public class GenericInvoiceListBox extends JScrollPane implements Relocalizable
    {
    /**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private JTable           				m_InvoiceTable;
    private GenericInvoiceListModel			m_Invoices;
    private TableSorter						m_InvoiceSorter;
         
//***************************************************************************
//* Class Constants                                                         *
//***************************************************************************

    private static int c_CellMargin = 7;
 
//***************************************************************************
//* Internal Class Definitions	                                            *
//***************************************************************************

//***************************************************************************
//* Constructor(s)                                                          *
//***************************************************************************

public GenericInvoiceListBox (GenericInvoiceListModel p_ListModel)
    {	
	super ();
      
    m_Invoices = p_ListModel;
    
    m_InvoiceSorter = new TableSorter ();
    m_InvoiceSorter.setTableModel(m_Invoices);
    
    m_InvoiceTable = new JTable (m_InvoiceSorter);
    m_InvoiceTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    m_InvoiceTable.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
        
    m_InvoiceTable.setColumnSelectionAllowed (false);
    m_InvoiceTable.setShowGrid (false);
    
    m_InvoiceSorter.setTableHeader(m_InvoiceTable.getTableHeader());
    
    this.setViewportView (m_InvoiceTable);   
    }

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

public void addListSelectionListener (ListSelectionListener p_Listener)
    {
    ListSelectionModel	l_Selection;	
    
    l_Selection = m_InvoiceTable.getSelectionModel();
    l_Selection.addListSelectionListener (p_Listener);
    }

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

public void addMouseListener (MouseListener p_Listener)
    {
    m_InvoiceTable.addMouseListener (p_Listener);
    }    

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

public void addKeyListener (KeyListener p_Listener)
    {
    m_InvoiceTable.addKeyListener (p_Listener);
    }    
 
//---------------------------------------------------------------------------

private int modelIndex (int p_RowInView)
	{
	int	l_ModelRow;
	
	l_ModelRow = p_RowInView;
	
	if (m_InvoiceSorter.isSorting())
		{
		l_ModelRow = m_InvoiceSorter.modelIndex(l_ModelRow);
		}
	
	return l_ModelRow;
	}

//---------------------------------------------------------------------------
//Sets the preferred width of the visible column specified by vColIndex. The column
// will be just wide enough to show the column head and the widest cell in the column.
// margin pixels are added to the left and right
// (resulting in an additional width of 2*margin pixels).
//---------------------------------------------------------------------------

public void packColumn (int p_Column, int p_Margin) 
	{
	DefaultTableColumnModel	l_ColumnModel;
	TableColumn 				l_Column;
	TableCellRenderer		l_Renderer;
	Component				l_Component;
	
	int		   				l_Width;
    int						l_Row;
	
	l_ColumnModel = (DefaultTableColumnModel)m_InvoiceTable.getColumnModel();
	l_Column = l_ColumnModel.getColumn(p_Column);
	l_Width = 0;

    // First step consists in getting width of column header

    l_Renderer = l_Column.getHeaderRenderer();
    if (l_Renderer == null) 
    		{
    		l_Renderer = m_InvoiceTable.getTableHeader().getDefaultRenderer();
    		}
    
    l_Component = l_Renderer.getTableCellRendererComponent(m_InvoiceTable,
    													    l_Column.getHeaderValue(), 
    													    false, false, 0, 0);
    l_Width = l_Component.getPreferredSize().width;

    // Next we're going to iterate through all the rows of this columns, in order to
    // to find the widest one

    for (l_Row=0; l_Row < m_InvoiceTable.getRowCount(); l_Row++) 
    		{
    		l_Renderer = m_InvoiceTable.getCellRenderer(l_Row, p_Column);
         
       		try {
    			l_Component = l_Renderer.getTableCellRendererComponent(m_InvoiceTable, 
    				                                               	   m_InvoiceTable.getValueAt(l_Row, p_Column), 
    				                                               	   false, false, l_Row, p_Column);
    			}
    		catch (Exception p_Exception)
    			{
    			// TODO Nasty Workaround
    			// Invoice Renderer sometimes throws unexplicable NullPointerExceptions.
    			// Not catching them results in Table not being properly packed.
    			}
 		
    		l_Width = Math.max (l_Width, l_Component.getPreferredSize().width);
    		}

    // Add margin
    l_Width += 2*p_Margin;

    // Set the width
    l_Column.setPreferredWidth(l_Width);
	}

//---------------------------------------------------------------------------
//Returns the preferred height of a row.
// The result is equal to the tallest cell in the row.
//---------------------------------------------------------------------------

public void packRow (int p_Row, int p_Margin) 
	{
    int					l_RowHeight;
    int					l_ComponentHeight;
	int					l_Column;
    TableCellRenderer	l_Renderer;
    Component			l_Component;
    
    // Get the current default height for all rows
    l_RowHeight = m_InvoiceTable.getRowHeight();

    // Determine highest cell in the row
    for (l_Column = 0; l_Column < m_InvoiceTable.getColumnCount(); l_Column++) 
    		{
    		l_Renderer = m_InvoiceTable.getCellRenderer(p_Row, l_Column);
    		l_Component = m_InvoiceTable.prepareRenderer(l_Renderer, p_Row, l_Column);
    		l_ComponentHeight = l_Component.getPreferredSize().height + 2*p_Margin;
    		l_RowHeight = Math.max (l_RowHeight, l_ComponentHeight);
    		}
    
    if (m_InvoiceTable.getRowHeight() != l_RowHeight)
    		m_InvoiceTable.setRowHeight (p_Row,l_RowHeight);
	}

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

private boolean setSelection (int p_Row)
	{
	ListSelectionModel	l_Selection;	
	JScrollBar			l_ScrollBar;
	float				l_ScrollValue;
	boolean 			l_Selected = false;
	    
	if ((p_Row >= 0) && (p_Row < m_InvoiceTable.getRowCount()))
        {
		l_Selection = m_InvoiceTable.getSelectionModel();
		l_Selection.setSelectionInterval (p_Row,p_Row);
			
		l_ScrollBar = getVerticalScrollBar ();
			
		l_ScrollValue  = (float) p_Row / (float) m_Invoices.getRowCount();
		l_ScrollValue *= (l_ScrollBar.getMaximum() - l_ScrollBar.getMinimum()); 
			
		l_ScrollBar.setValue ((int)l_ScrollValue);
			
		l_Selected = true;
		m_InvoiceTable.revalidate();
        }
	   
	return (l_Selected);
	}

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

public void relocalize ()
    {
    // Make sure JTable re-creates columns using re-localized headers
        
    m_InvoiceTable.createDefaultColumnsFromModel ();
    }

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

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

public void setInvoiceRenderer (DefaultTableCellRenderer p_Renderer)
	{
    int l_Count;
	
	for (l_Count=0; l_Count < m_Invoices.getColumnCount(); l_Count++)
		{
		if (m_Invoices.getColumnClass(l_Count) != null)	
			m_InvoiceTable.setDefaultRenderer (m_Invoices.getColumnClass(l_Count), p_Renderer);
		}
	}

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

public void setTableCellEditor (TableCellEditor p_CellEditor, int p_Column)
	{
	TableColumn	l_Column;
	
	if ((p_Column >= 0) && p_Column < m_Invoices.getColumnCount())
		{
		l_Column = m_InvoiceTable.getColumnModel().getColumn(0);
		l_Column.setCellEditor (p_CellEditor);		
		}
	}

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

public JTable getTable ()
	{
	return m_InvoiceTable;
	}

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

public void addInvoice (Invoice p_Invoice)
    {
    if (p_Invoice != null)
        {
        m_Invoices.addInvoice (p_Invoice);
        m_InvoiceTable.revalidate();
        }
    }

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

public void updateResults (Vector <Invoice> p_Invoices)
    {
    Invoice  l_Invoice;
    int     l_InvoiceCount;
    
    if (p_Invoices == null) return;
        
    for (l_InvoiceCount = 0; l_InvoiceCount < p_Invoices.size(); l_InvoiceCount++)
        {
        l_Invoice = p_Invoices.elementAt(l_InvoiceCount);
            
        if (!this.containsInvoice (l_Invoice)) addInvoice (l_Invoice);
        }
    }

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

public void removeSelectedInvoices ()
    {
    int []      l_SelectedRows;
    
    int         l_Selection;
    int			l_ModelRow;
    
    l_Selection = m_InvoiceTable.getSelectedRowCount();
    
    if (l_Selection > 0)
        {
        l_SelectedRows    = m_InvoiceTable.getSelectedRows ();
       
        for (l_Selection = l_SelectedRows.length - 1; l_Selection >= 0; l_Selection--)
            {
        	l_ModelRow = this.modelIndex (l_SelectedRows [l_Selection]);
        	m_Invoices.removeInvoiceAt (l_ModelRow);
            }
        
        m_InvoiceTable.clearSelection();
        m_InvoiceTable.revalidate();
        }
    }

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

public void removeAllInvoices ()
    {
	m_Invoices.removeAllInvoices();
    m_InvoiceTable.clearSelection();
    m_InvoiceTable.revalidate();
    }

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

public Invoice[] getSelectedInvoices ()
    {
	Invoice []  l_SelectedInvoices = null;    
    int []      l_SelectedRows;   
    int         l_Selection;
    int			l_ModelRow;
    
    l_Selection = m_InvoiceTable.getSelectedRowCount();
    
    if (l_Selection > 0)
        {
        l_SelectedRows    = m_InvoiceTable.getSelectedRows ();
        l_SelectedInvoices = new Invoice [l_Selection];
        
        for (l_Selection = 0; l_Selection < l_SelectedRows.length; l_Selection++)
            {
        	l_ModelRow = this.modelIndex(l_SelectedRows [l_Selection]);
        	l_SelectedInvoices [l_Selection] = m_Invoices.getInvoiceAt (l_ModelRow);
            }
        }

    return (l_SelectedInvoices);
    }

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

public int findInvoice (String p_InvoiceNumber)
    {
    return m_Invoices.findInvoice (p_InvoiceNumber);
    }    

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

public boolean containsInvoice (Invoice p_Invoice)
	{
	return m_Invoices.containsInvoice (p_Invoice);
	}

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

public void setInvoiceAt (Invoice p_Invoice, int p_Row)
	{
	m_Invoices.setInvoiceAt(p_Invoice, p_Row);
	}

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

public boolean selectInvoice (String p_InvoiceNumber)
    {
    int			l_SelectedRow;
   
	l_SelectedRow = m_Invoices.findInvoice (p_InvoiceNumber);
    l_SelectedRow = m_InvoiceSorter.viewIndex(l_SelectedRow);
	
	return (this.setSelection(l_SelectedRow));
    }
  
//---------------------------------------------------------------------------

public boolean selectNextInvoice ()
	{
    int l_SelectedRow	 = 0;
     
    l_SelectedRow = m_InvoiceTable.getSelectedRow ();
    if (l_SelectedRow >= 0) 
    	 l_SelectedRow++;
    else l_SelectedRow = 0;
    return (this.setSelection(l_SelectedRow));
	}

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

public boolean selectPreviousInvoice ()
	{
	int l_SelectedRow = 0;
	
	l_SelectedRow = m_InvoiceTable.getSelectedRow ();
	if (l_SelectedRow >= 0) l_SelectedRow--;
					   else l_SelectedRow = m_InvoiceTable.getRowCount() - 1;
	return (this.setSelection(l_SelectedRow));
	}

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

public void selectFirstInvoice ()
	{
	this.setSelection(0);
	}

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

public void selectLastInvoice ()
	{
	int	l_LastRow;
	
	l_LastRow = m_InvoiceTable.getRowCount() - 1;
	this.setSelection(l_LastRow);
	}

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

public Invoice getSelectedInvoice ()
	{
	int     l_SelectedRow		= 0;
    int			l_ModelRow;
	Invoice	l_SelectedInvoice	= null;
	
	l_SelectedRow = m_InvoiceTable.getSelectedRow ();
	if (l_SelectedRow >= 0) 
		{
       	l_ModelRow = this.modelIndex(l_SelectedRow);
		l_SelectedInvoice = m_Invoices.getInvoiceAt(l_ModelRow);
		}
		
	return l_SelectedInvoice;
	}

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

public void setSelectedInvoice (Invoice p_Invoice)
	{
	int     l_SelectedRow	= 0;
	  
	if (p_Invoice == null) return;
	
	l_SelectedRow = m_InvoiceTable.getSelectedRow ();
	
	if (l_SelectedRow >= 0) 
		{
		l_SelectedRow = this.modelIndex(l_SelectedRow);
		m_Invoices.setInvoiceAt(p_Invoice,l_SelectedRow);
		m_InvoiceTable.invalidate();
		}
	}

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

public void setInvoices (Collection <Invoice> p_Invoices)
    {
    m_Invoices.setInvoices(p_Invoices);
    }    
 
//---------------------------------------------------------------------------

public Collection <Invoice> getInvoices ()
    {
    return m_Invoices.getInvoices();
    }    
    
//---------------------------------------------------------------------------

public int getNumberOfInvoices ()
	{
	return m_Invoices.getRowCount();
	}

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

public void packColumns ()
	{
	int l_Column;
	
	for (l_Column=0; l_Column < m_InvoiceTable.getColumnCount(); l_Column++)
		{
		packColumn (l_Column,c_CellMargin);
		}
	}

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

public void packRows ()
	{
	int l_Row;
	
	for (l_Row=0; l_Row < m_InvoiceTable.getRowCount(); l_Row++)
		{
		packRow (l_Row,c_CellMargin);
		}
	}

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