/*
 *  PHEX - The pure-java Gnutella-servent.
 *  Copyright (C) 2001 - 2004 Gregor Koukkoullis ( phex <at> kouk <dot> de )
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program 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 General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
package phex.gui.tabs;

import java.awt.event.*;

import javax.swing.*;
import javax.swing.event.*;
import javax.xml.bind.JAXBException;

import phex.event.SharedFilesChangeListener;
import phex.gui.common.*;
import phex.gui.common.table.*;
import phex.gui.models.*;
import phex.share.*;
import phex.utils.*;
import phex.xml.*;

import com.jgoodies.forms.builder.PanelBuilder;
import com.jgoodies.forms.layout.*;

public class LibraryTab extends FWTab
{
    private static final String SHARED_FILES_TABLE_IDENTIFIER = "SharedFilesTable";
    
    private JLabel sharedFilesLabel;
    private FWTable sharedFilesTable;
    private JScrollPane sharedFilesTableScrollPane;
    private SharedFilesTableModel sharedFilesModel;
    private FWTableColumnModel sharedFilesColumnModel;
    
    private FileAdministration fileAdmin;
    
    public LibraryTab()
    {
        super( MainFrame.LIBRARY_TAB_ID, Localizer.getString( "Library" ),
            GUIRegistry.getInstance().getIconFactory().getIcon( "Library" ),
            Localizer.getString( "TTTLibrary" ), Localizer.getChar(
            "LibraryMnemonic"), KeyStroke.getKeyStroke( Localizer.getString(
            "LibraryAccelerator" ) ), MainFrame.LIBRARY_TAB_INDEX );
        fileAdmin = ShareManager.getInstance().getFileAdministration();
    }
    
    public void initComponent( XJBGUISettings guiSettings )
    {
        CellConstraints cc = new CellConstraints();
        FormLayout layout = new FormLayout(
            "4dlu, fill:d:grow, 4dlu", // columns
            "3dlu, p, 1dlu, p, 1dlu, fill:d:grow, 1dlu, p, 3dlu"); //rows
        PanelBuilder tabBuilder = new PanelBuilder( this, layout );
        
        tabBuilder.addSeparator( Localizer.getString("Library"),
            cc.xy( 2, 2 ) );
            
        sharedFilesLabel = new JLabel( " " );
        sharedFilesLabel.setHorizontalAlignment( JLabel.RIGHT );
        fileAdmin.addSharedFilesChangeListener(
            new SharedFilesChangeHandler() );
        tabBuilder.add( sharedFilesLabel, cc.xy( 2, 4 ) );

        sharedFilesModel = new SharedFilesTableModel();
        XJBGUITable xjbTable = GUIUtils.getXJBGUITableByIdentifier(
            guiSettings, SHARED_FILES_TABLE_IDENTIFIER );
        buildSharedFilesTableColumnModel( xjbTable );

        sharedFilesTable = new FWTable( new FWSortedTableModel( sharedFilesModel ),
            sharedFilesColumnModel );
        sharedFilesTable.activateAllHeaderActions();
        sharedFilesTable.setAutoResizeMode( JTable.AUTO_RESIZE_OFF );
        sharedFilesTable.getSelectionModel().addListSelectionListener(
            new SelectionHandler() );
        sharedFilesTableScrollPane = FWTable.createFWTableScrollPane( sharedFilesTable );
        
        tabBuilder.add( sharedFilesTableScrollPane, cc.xy( 2, 6 ) );
            
        FWToolBar shareToolbar = new FWToolBar( JToolBar.HORIZONTAL );
        shareToolbar.setBorderPainted( false );
        shareToolbar.setFloatable( false );
        tabBuilder.add( shareToolbar, cc.xy( 2, 8 ) );

        JButton shareRescanButton = new JButton( Localizer.getString( "Rescan" ) );
        shareToolbar.add(shareRescanButton);
        shareRescanButton.addActionListener(new ShareRescanHandler());
    }
    
    /**
     * This is overloaded to update the table size for the progress bar on
     * every UI update. Like font size change!
     */
    public void updateUI()
    {
        super.updateUI();
        if ( sharedFilesTableScrollPane != null )
        {
            FWTable.updateFWTableScrollPane( sharedFilesTableScrollPane );
        }
    }
    
    //////////////////////////////////////////////////////////////////////////
    /// XML serializing and deserializing
    //////////////////////////////////////////////////////////////////////////

    private void buildSharedFilesTableColumnModel( XJBGUITable tableSettings )
    {
        int[] columnIds = SharedFilesTableModel.getColumnIdArray();
        XJBGUITableColumnList columnList = null;
        if ( tableSettings != null )
        {
            columnList = tableSettings.getTableColumnList();
        }

        sharedFilesColumnModel = new FWTableColumnModel( sharedFilesModel,
            columnIds, columnList );
    }

    public void appendXJBGUISettings( XJBGUISettings xjbSettings )
        throws JAXBException
    {
        super.appendXJBGUISettings( xjbSettings );

        XJBGUITableColumnList xjbList = sharedFilesColumnModel.createXJBGUITableColumnList();
        XJBGUITable xjbTable = ObjectFactory.createXJBGUITable();
        xjbTable.setTableColumnList( xjbList );
        xjbTable.setTableIdentifier( SHARED_FILES_TABLE_IDENTIFIER );
        xjbSettings.getTableList().getTableList().add( xjbTable );
    }
    
    //////////////////////////////////////////////////////////////////////////
    /// Listeners
    //////////////////////////////////////////////////////////////////////////
    
    private class SelectionHandler implements ListSelectionListener
    {
        public void valueChanged(ListSelectionEvent e)
        {
            if ( !e.getValueIsAdjusting() )
            {
                refreshTabActions();
            }
        }
    }
    
    private class ShareRescanHandler implements ActionListener
    {
        public void actionPerformed(ActionEvent e)
        {
            ShareManager.getInstance().getFileAdministration().rescan( true, true );
        }
    }
    
    private class SharedFilesChangeHandler implements SharedFilesChangeListener
    {
        /**
         * Called if a shared file changed.
         */
        public void sharedFileChanged( int position )
        {
        }

        /**
         * Called if a shared file was added.
         */
        public void sharedFileAdded( int position )
        {
            updateLabel();
        }

        /**
         * Called if a shared file was removed.
         */
        public void sharedFileRemoved( int position )
        {
            updateLabel();
        }

        /**
         * Called if all shared files changed.
         */
        public void allSharedFilesChanged( )
        {
            updateLabel();
        }

        private void updateLabel()
        {
            StringBuffer buffer = new StringBuffer( );
            buffer.append( '(' );
            buffer.append( fileAdmin.getFileCount() );
            buffer.append( " / " );
            buffer.append( StrUtil.formatSizeBytes( ((long)fileAdmin.getTotalFileSizeInKb()) * 1024L ) ).append(')');

            sharedFilesLabel.setText( buffer.toString() );
        }
    }
}