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

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

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.DefaultTableColumnModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;

import lu.tudor.santec.gecamed.billing.ejb.entity.beans.InvoiceTemplate;
import lu.tudor.santec.gecamed.billing.gui.BillingModule;
import lu.tudor.santec.gecamed.billing.utils.BillingUserSettings;
import lu.tudor.santec.i18n.Relocalizable;

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

public class TemplateListBox extends JScrollPane implements Relocalizable
    {
    /**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private JTable           		m_TemplateTable;
    private TemplateListModel		m_Templates;
    private TemplateRenderer		m_TemplateRenderer;
    private DescriptionRenderer		m_DescriptionRenderer;
    
//    private GhostGlassPane			m_GhostPane;
     
//***************************************************************************
//* Class Constants                                                         *
//***************************************************************************

//***************************************************************************
//* Class Constants                                                         *
//***************************************************************************

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

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

public TemplateListBox ()
    {	
	super ();
    
    int			l_Count;	
    TableColumn  l_Column;
    
    m_Templates  = new TemplateListModel ();
     
    m_TemplateTable = new JTable ();
    m_TemplateTable.setModel(m_Templates);
    //m_RateTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
    m_TemplateTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    m_TemplateTable.setDragEnabled(true);
    m_TemplateTable.setTransferHandler (new TableTransferHandler());
     
    m_TemplateRenderer = new TemplateRenderer ();
    
    for (l_Count=0; l_Count < m_Templates.getColumnCount(); l_Count++)
    	{
    	if (m_Templates.getColumnClass(l_Count) != null)	
    		m_TemplateTable.setDefaultRenderer (m_Templates.getColumnClass(l_Count), m_TemplateRenderer);
     	}
  
    m_DescriptionRenderer = new DescriptionRenderer();
    
    l_Column = m_TemplateTable.getColumnModel().getColumn(TemplateListModel.c_DescriptionColumn);
    l_Column.setCellRenderer(m_DescriptionRenderer);

    m_TemplateTable.setColumnSelectionAllowed (false);
    m_TemplateTable.setShowGrid (false);
        
    this.setViewportView (m_TemplateTable);
    }

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

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

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

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

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

public void addKeyListener (KeyListener p_Listener)
    {
	m_TemplateTable.addKeyListener (p_Listener);
    }    

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

//public void setGhostPane (GhostGlassPane p_GhostPane)
//	{
//    m_GhostPane = p_GhostPane;
//	m_TemplateTable.addMouseListener(new GhostTableRowAdapter(m_GhostPane, "row"));
//	}

//---------------------------------------------------------------------------
//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_TemplateTable.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_TemplateTable.getTableHeader().getDefaultRenderer();
    		}
    
    l_Component = l_Renderer.getTableCellRendererComponent(m_TemplateTable,
    													    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_TemplateTable.getRowCount(); l_Row++) 
    		{
    		l_Renderer = m_TemplateTable.getCellRenderer(l_Row, p_Column);
    		l_Component = l_Renderer.getTableCellRendererComponent(m_TemplateTable, 
    															m_TemplateTable.getValueAt(l_Row, p_Column), 
    				                                               false, false, l_Row, p_Column);
        
    		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_TemplateTable.getRowHeight();

    // Determine highest cell in the row
    for (l_Column = 0; l_Column < m_TemplateTable.getColumnCount(); l_Column++) 
    		{
    		l_Renderer = m_TemplateTable.getCellRenderer(p_Row, l_Column);
    		l_Component = m_TemplateTable.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_TemplateTable.getRowHeight() != l_RowHeight)
    		m_TemplateTable.setRowHeight (p_Row,l_RowHeight);
	}

//---------------------------------------------------------------------------
/**
 * 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_InvoiceRenderer.relocalize ();
    m_TemplateTable.createDefaultColumnsFromModel ();
    }

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

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

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

public void addTemplate (InvoiceTemplate p_Template)
    {
    if (p_Template != null)
        {
        m_Templates.addTemplate (p_Template);
        m_TemplateTable.validate();
        }
    }

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

public void removeSelectedTemplate ()
    {
    int []      l_SelectedRows;    
    int         l_Selection;
    
    l_Selection = m_TemplateTable.getSelectedRowCount();
    
    if (l_Selection > 0)
        {
        l_SelectedRows    = m_TemplateTable.getSelectedRows ();
        if (l_SelectedRows != null) 
        	{
        	m_Templates.removeTemplateAt (l_SelectedRows[0]);
        	m_TemplateTable.clearSelection();
        	m_TemplateTable.validate();
        	}
        }
    }

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

public void removeAllTemplates ()
    {
	m_Templates.removeAllTemplates();
	m_TemplateTable.clearSelection();
	m_TemplateTable.validate();
    }

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

public InvoiceTemplate getSelectedTemplate ()
    {
	InvoiceTemplate	l_SelectedTemplate = null; 
    int []   		l_SelectedRows;   
    int      		l_Selection;
     
    l_Selection = m_TemplateTable.getSelectedRowCount();
    
    if (l_Selection == 1)
        {
        l_SelectedRows    = m_TemplateTable.getSelectedRows ();
        if (l_SelectedRows != null)
        	{
        	l_SelectedTemplate = m_Templates.getTemplateAt (l_SelectedRows[0]);
        	}
         }

    return (l_SelectedTemplate);
    }

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

public int getTemplateCount ()
	{
	return m_Templates.getRowCount();
	}

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

public void setTemplates (Collection <InvoiceTemplate> p_Templates)
    {
    Integer	l_TemplateButtons;
	
	m_Templates.setTemplates(p_Templates);
    	
	l_TemplateButtons = (Integer) BillingModule.getUserSetting (BillingUserSettings.c_TemplateButtonsSetting);
	if (l_TemplateButtons instanceof Integer)
		{
		m_TemplateRenderer.setNumberOfHighlightedRows(l_TemplateButtons.intValue());
		m_DescriptionRenderer.setNumberOfHighlightedRows(l_TemplateButtons.intValue());
		}
    }    
 
//---------------------------------------------------------------------------

public int findTemplate (String p_Shortcut)
	{
	return m_Templates.findTemplate(p_Shortcut);
	}

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

public boolean selectTemplate (String p_Shortcut)
    {
    ListSelectionModel	l_Selection;	
    JScrollBar			l_ScrollBar;
    int 				l_Row;
    float				l_ScrollValue;
    boolean 			l_Selected = false;
    
    l_Row 		= m_Templates.findTemplate(p_Shortcut);
    l_Selection = m_TemplateTable.getSelectionModel();
	
    if (l_Row >= 0)
        {
    	l_Selection.setSelectionInterval (l_Row,l_Row);
		
    	l_ScrollBar = getVerticalScrollBar ();
		
    	l_ScrollValue  = (float) l_Row / (float) m_Templates.getRowCount();
    	l_ScrollValue *= (l_ScrollBar.getMaximum() - l_ScrollBar.getMinimum()); 
		
    	l_ScrollBar.setValue ((int)l_ScrollValue);
		
    	l_Selected = true;
        }
    else
    	l_Selection.clearSelection();
   
    return (l_Selected);
    }

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

public void	setTemplateAt (InvoiceTemplate p_Template, int p_Row)
	{
	m_Templates.setTemplateAt (p_Template, p_Row);
	m_TemplateTable.validate();
	}

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

public Collection <InvoiceTemplate> getTemplates ()
    {
    return m_Templates.getTemplates();
    }    
    
//---------------------------------------------------------------------------

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

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

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



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