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

import java.util.Comparator;

import javax.swing.ListSelectionModel;
import javax.swing.event.*;

import phex.download.swarming.*;
import phex.event.DownloadSegmentsChangeListener;
import phex.gui.common.*;
import phex.gui.common.table.*;
import phex.gui.comparator.*;
import phex.gui.renderer.*;
import phex.utils.Localizer;

public class SWSegmentTableModel extends FWSortableTableModel
{
    /**
     * The unique column id is not allowed to ever change over Phex releases. It
     * is used when serializing column information. The column id is containd in
     * the identifier field of the TableColumn.
     */
    public static final int FROM_COLUMN_ID = 1001;
    public static final int PROGRESS_COLUMN_ID = 1002;
    public static final int SIZE_COLUMN_ID = 1003;
    public static final int RATE_COLUMN_ID = 1004;

    public static final int FROM_MODEL_INDEX = 0;
    public static final int PROGRESS_MODEL_INDEX = 1;
    public static final int SIZE_MODEL_INDEX = 2;
    public static final int RATE_MODEL_INDEX = 3;

    private static String[] tableColumns;
    private static Class[] tableClasses;

    /**
     * Initialize super tableColumns field
     */
    static
    {
        tableColumns = new String[]
        {
            Localizer.getString( "From" ),
            Localizer.getString( "PercentSign" ),
            Localizer.getString( "Size" ),
            Localizer.getString( "Rate" )
        };

        tableClasses = new Class[]
        {
            Long.class,
            ProgressCellRenderer.class,
            TransferSizeCellRenderer.class,
            TransferRateCellRenderer.class,
        };
    }

    private SwarmingManager swarmingMgr;

    /**
     * The currently displayed download file of the model.
     */
    private SWDownloadFile downloadFile;

    private FWTable downloadTable;

    private DownloadSegmentsListener changeListener;

    /**
     * @param downloadTable The constructor takes the download JTable. This is
     * necessary to get informed of the selection changes of the download table.
     */
    public SWSegmentTableModel( FWTable aDownloadTable )
    {
        super( tableColumns, tableClasses );
        swarmingMgr = SwarmingManager.getInstance();
        downloadTable = aDownloadTable;
        downloadTable.getSelectionModel().addListSelectionListener(
            new DownloadSelectionChangeHandler() );
        changeListener = new DownloadSegmentsListener();
    }

    public int getRowCount()
    {
        if ( downloadFile == null )
        {
            return 0;
        }
        return downloadFile.getSegmentCount();
    }

    public Object getValueAt( int row, int column )
    {
        SWDownloadSegment segment = downloadFile.getSegment( row );
        if ( segment == null )
        {
            fireTableRowsDeleted( row, row );
            return "";
        }

        switch( column )
        {
            case FROM_MODEL_INDEX:
                return segment.getStartOffsetObject();
            case PROGRESS_MODEL_INDEX:
                return segment.getProgress();
            case SIZE_MODEL_INDEX:
            case RATE_MODEL_INDEX:
                // 3: handled by TransferSizeCellRenderer
                // 4: handled by TransferRateCellRenderer
                return segment;
            default:
                return "";
        }
    }

    /**
     * Returns the most comparator that is used for sorting of the cell values
     * in the column. This is used by the FWSortedTableModel to perform the
     * sorting. If not overwritten the method returns null causing the
     * FWSortedTableModel to use a NaturalComparator. It expects all Objects that
     * are returned from getComparableValueAt() to implement the Comparable interface.
     *
     */
    public Comparator getColumnComparator( int column )
    {
        switch( column )
        {
            case SIZE_MODEL_INDEX:
                return new TransferSizeComparator();
            case RATE_MODEL_INDEX:
                return new TransferRateComparator();
            // for all other columns use default comparator
            default:
                return null;
        }
    }

    /**
     * Maps the unique column id to the model index. This needs to be done to
     * be able identify columns and there index after changes in Phex releases.
     * The unique column id is not allowed to ever change over Phex releases. It
     * is used when serializing column information. The column id is containd in
     * the identifier field of the TableColumn.
     */
    public int mapColumnIDToModelIndex( int columnId )
    {
        switch( columnId )
        {
            case FROM_COLUMN_ID:
                return FROM_MODEL_INDEX;
            case PROGRESS_COLUMN_ID:
                return PROGRESS_MODEL_INDEX;
            case SIZE_COLUMN_ID:
                return SIZE_MODEL_INDEX;
            case RATE_COLUMN_ID:
                return RATE_MODEL_INDEX;
            default:
                return -1;
        }
    }

    /**
     * Indicates if a column is hideable.
     */
    public boolean isColumnHideable( int columnID )
    {
        if ( columnID == PROGRESS_COLUMN_ID )
        {
            return false;
        }
        return true;
    }

    private class DownloadSelectionChangeHandler implements ListSelectionListener
    {
        public void valueChanged(ListSelectionEvent e)
        {
            if ( !e.getValueIsAdjusting() )
            {
                ListSelectionModel model = (ListSelectionModel) e.getSource();
                int viewIdx = model.getLeadSelectionIndex();
                int modelIdx = downloadTable.convertRowIndexToModel( viewIdx );
                SWDownloadFile tmpDownloadFile = swarmingMgr.getDownloadFile( modelIdx );

                if ( tmpDownloadFile != downloadFile )
                {
                    if ( downloadFile != null )
                    {
                        downloadFile.removeDownloadSegmentChangeListener(
                            changeListener );
                    }
                    downloadFile = tmpDownloadFile;
                    if ( downloadFile != null )
                    {
                        downloadFile.addDownloadSegmentChangeListener(
                            changeListener );
                    }
                    fireTableDataChanged();
                }
            }
        }
    }

    private class DownloadSegmentsListener
        implements DownloadSegmentsChangeListener
    {
        private LazyEventQueue lazyEventQueue;

        public DownloadSegmentsListener()
        {
            lazyEventQueue = GUIRegistry.getInstance().getLazyEventQueue();
        }

        /**
         * Called if a download segment changed.
         */
        public void downloadSegmentChanged( int position )
        {
            lazyEventQueue.addTableModelEvent(
                new TableModelEvent( SWSegmentTableModel.this, position, position,
                    TableModelEvent.ALL_COLUMNS, TableModelEvent.UPDATE ) );
        }

        /**
         * Called if a download segment was added.
         */
        public void downloadSegmentAdded( int position )
        {
            fireTableChanged( new TableModelEvent(SWSegmentTableModel.this,
                position, position, TableModelEvent.ALL_COLUMNS,
                TableModelEvent.INSERT ) );
        }

        /**
         * Called if a download segment was removed.
         */
        public void downloadSegmentRemoved( int position )
        {
            fireTableChanged( new TableModelEvent(SWSegmentTableModel.this,
                position, position, TableModelEvent.ALL_COLUMNS,
                TableModelEvent.DELETE ) );
        }
    }
}