/***************************************************************************
    smb4kshareslistview_part  -  This Part includes the shares list view
    of Smb4K.
                             -------------------
    begin                : Sa Jun 30 2007
    copyright            : (C) 2007 by Alexander Reinholdt
    email                : dustpuppy@users.berlios.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., 51 Franklin Street, Fifth Floor, Boston,   *
 *   MA  02110-1301 USA                                                    *
 ***************************************************************************/

// TQt includes
#include <tqheader.h>

// KDE includes
#include <tdeglobal.h>
#include <kstdaction.h>
#include <tdelocale.h>
#include <tdeaboutdata.h>
#include <tdelocale.h>
#include <tdeaction.h>
#include <tdeshortcut.h>
#include <kdebug.h>
#include <tdepopupmenu.h>
#include <kiconloader.h>
#include <tdeactionclasses.h>

// application specific includes
#include "smb4kshareslistview_part.h"
#include "smb4kshareslistview.h"
#include "smb4kshareslistviewitem.h"
#include "../dialogs/smb4ksynchronizationdialog.h"
#include "../core/smb4kshare.h"
#include "../core/smb4kcore.h"
#include "../core/smb4ksettings.h"


TDEInstance *Smb4KSharesListViewPartFactory::m_instance = 0L;
TDEAboutData *Smb4KSharesListViewPartFactory::m_about = 0L;


Smb4KSharesListViewPart::Smb4KSharesListViewPart( TQWidget *parentWidget, const char *widgetName,
                                                  TQObject *parent, const char *name )
: KParts::Part( parent, name )
{
  // First of all We need an instance:
  setInstance( Smb4KSharesListViewPartFactory::instance() );

  // Set the XML file:
  setXMLFile( "smb4kshareslistview_part.rc" );

  // Set the widget of this part:
  m_widget = new Smb4KSharesListView( parentWidget, widgetName );
  setWidget( m_widget );

  // Set up the actions.
  // Do not put this before setWidget() or the shortcuts
  // will not be shown.
  setupActions();

  // Import the shares:
  slotMountedShares();

  // Load settings:
  loadSettings();

  // Add some connections:
  connect( Smb4KCore::mounter(),      TQ_SIGNAL( updated() ),
           this,                      TQ_SLOT( slotMountedShares() ) );

  connect( Smb4KCore::synchronizer(), TQ_SIGNAL( state( int ) ),
           this,                      TQ_SLOT( slotSynchronizationState( int ) ) );

  connect( m_widget,                  TQ_SIGNAL( contextMenuRequested( TQListViewItem *, const TQPoint & , int) ),
           this,                      TQ_SLOT( slotContextMenuRequested( TQListViewItem *, const TQPoint &, int ) ) );

  connect( m_widget,                  TQ_SIGNAL( selectionChanged( TQListViewItem * ) ),
           this,                      TQ_SLOT( slotSelectionChanged( TQListViewItem * ) ) );

  connect( m_widget,                  TQ_SIGNAL( pressed( TQListViewItem * ) ),
           this,                      TQ_SLOT( slotMouseButtonPressed( TQListViewItem * ) ) );

  connect( m_widget,                  TQ_SIGNAL( executed( TQListViewItem * ) ),
           this,                      TQ_SLOT( slotFilemanager() ) );
}


Smb4KSharesListViewPart::~Smb4KSharesListViewPart()
{
}


void Smb4KSharesListViewPart::setupActions()
{
  // Create the actions:
  TDEAction *unmount =   new TDEAction( i18n( "&Unmount" ), "drive-harddisk-unmounted", TDEShortcut( CTRL+Key_U ),
                                    this, TQ_SLOT( slotUnmountShare() ),
                                    actionCollection(), "unmount_action" );
#ifdef __linux__
  TDEAction *force =     new TDEAction( i18n( "&Force Unmounting" ), "drive-harddisk-unmounted", TDEShortcut( CTRL+Key_F ),
                                    this, TQ_SLOT( slotForceUnmountShare() ),
                                    actionCollection(), "force_unmount_action" );
#endif
  TDEAction *all =       new TDEAction( i18n( "U&nmount All" ), "gear", TDEShortcut( CTRL+Key_N ),
                                    this, TQ_SLOT( slotUnmountAllShares() ),
                                    actionCollection(), "unmount_all_action" );
  TDEAction *sync =      new TDEAction( i18n( "S&ynchronize" ), "go-bottom", TDEShortcut( CTRL+Key_Y ),
                                    this, TQ_SLOT( slotSynchronize() ),
                                    actionCollection(), "synchronize_action" );
  TDEAction *konsole =   new TDEAction( i18n( "Open with Konso&le" ), "terminal", TDEShortcut( CTRL+Key_L ),
                                    this, TQ_SLOT( slotKonsole() ),
                                    actionCollection(), "konsole_action" );
  TDEAction *konq =      new TDEAction( i18n( "Open with &Konqueror" ), "kfm_home", TDEShortcut( CTRL+Key_K ),
                                    this, TQ_SLOT( slotFilemanager() ),
                                    actionCollection(), "filemanager_action" );

  // Disable all actions for now:
  unmount->setEnabled( false );
#ifdef __linux__
  force->setEnabled( false );
#endif
  all->setEnabled( false );
  sync->setEnabled( false );
  konsole->setEnabled( false );
  konq->setEnabled( false );

  // Insert the actions into the menu:
  m_menu = new TDEActionMenu( this, "SharesListViewMenu" );
  m_menu->popupMenu()->insertTitle( SmallIcon( "drive-harddisk-mounted" ), i18n( "Shares" ), 0 );
  m_menu->insert( unmount, -1 );
#ifdef __linux__
  m_menu->insert( force, -1 );
#endif
  m_menu->insert( all, -1 );
  m_menu->popupMenu()->insertSeparator( -1 );
  m_menu->insert( sync, -1 );
  m_menu->popupMenu()->insertSeparator( -1 );
  m_menu->insert( konsole, -1 );
  m_menu->insert( konq, -1 );
}


void Smb4KSharesListViewPart::loadSettings()
{
#ifdef __linux__
  actionCollection()->action( "force_unmount_action" )->setEnabled( Smb4KSettings::useForceUnmount() );
#endif

  m_widget->setColumnWidth( Smb4KSharesListView::Item, 10 );
  m_widget->setColumnWidthMode( Smb4KSharesListView::Item, TQListView::Maximum );
  m_widget->header()->setResizeEnabled( true, Smb4KSharesListView::Item );

  if ( Smb4KSettings::showOwner() )
  {
    m_widget->setColumnWidth( Smb4KSharesListView::Owner, 10 );
    m_widget->setColumnWidthMode( Smb4KSharesListView::Owner, TQListView::Maximum );
    m_widget->header()->setResizeEnabled( true, Smb4KSharesListView::Owner );
  }
  else
  {
    m_widget->setColumnWidth( Smb4KSharesListView::Owner, 0 );
    m_widget->setColumnWidthMode( Smb4KSharesListView::Owner, TQListView::Manual );
    m_widget->header()->setResizeEnabled( false, Smb4KSharesListView::Owner );
  }

#ifndef __FreeBSD__
  if ( Smb4KSettings::showLogin() )
  {
    m_widget->setColumnWidth( Smb4KSharesListView::Login, 10 );
    m_widget->setColumnWidthMode( Smb4KSharesListView::Login, TQListView::Maximum );
    m_widget->header()->setResizeEnabled( true, Smb4KSharesListView::Login );
  }
  else
  {
    m_widget->setColumnWidth( Smb4KSharesListView::Login, 0 );
    m_widget->setColumnWidthMode( Smb4KSharesListView::Login, TQListView::Manual );
    m_widget->header()->setResizeEnabled( false, Smb4KSharesListView::Login );
  }
#endif

  if ( Smb4KSettings::showFileSystem() )
  {
    m_widget->setColumnWidth( Smb4KSharesListView::FileSystem, 10 );
    m_widget->setColumnWidthMode( Smb4KSharesListView::FileSystem, TQListView::Maximum );
    m_widget->header()->setResizeEnabled( true, Smb4KSharesListView::FileSystem );
  }
  else
  {
    m_widget->setColumnWidth( Smb4KSharesListView::FileSystem, 0 );
    m_widget->setColumnWidthMode( Smb4KSharesListView::FileSystem, TQListView::Manual );
    m_widget->header()->setResizeEnabled( false, Smb4KSharesListView::FileSystem );
  }

  if ( Smb4KSettings::showFreeDiskSpace() )
  {
    m_widget->setColumnWidth( Smb4KSharesListView::Free, 10 );
    m_widget->setColumnWidthMode( Smb4KSharesListView::Free, TQListView::Maximum );
    m_widget->header()->setResizeEnabled( true, Smb4KSharesListView::Free );
  }
  else
  {
    m_widget->setColumnWidth( Smb4KSharesListView::Free, 0 );
    m_widget->setColumnWidthMode( Smb4KSharesListView::Free, TQListView::Manual );
    m_widget->header()->setResizeEnabled( false, Smb4KSharesListView::Free );
  }

  if ( Smb4KSettings::showUsedDiskSpace() )
  {
    m_widget->setColumnWidth( Smb4KSharesListView::Used, 10 );
    m_widget->setColumnWidthMode( Smb4KSharesListView::Used, TQListView::Maximum );
    m_widget->header()->setResizeEnabled( true, Smb4KSharesListView::Used );
  }
  else
  {
    m_widget->setColumnWidth( Smb4KSharesListView::Used, 0 );
    m_widget->setColumnWidthMode( Smb4KSharesListView::Used, TQListView::Manual );
    m_widget->header()->setResizeEnabled( false, Smb4KSharesListView::Used );
  }

  if ( Smb4KSettings::showTotalDiskSpace() )
  {
    m_widget->setColumnWidth( Smb4KSharesListView::Total, 10 );
    m_widget->setColumnWidthMode( Smb4KSharesListView::Total, TQListView::Maximum );
    m_widget->header()->setResizeEnabled( true, Smb4KSharesListView::Total );
  }
  else
  {
    m_widget->setColumnWidth( Smb4KSharesListView::Total, 0 );
    m_widget->setColumnWidthMode( Smb4KSharesListView::Total, TQListView::Manual );
    m_widget->header()->setResizeEnabled( false, Smb4KSharesListView::Total );
  }

  if ( Smb4KSettings::showDiskUsage() )
  {
    m_widget->setColumnWidth( Smb4KSharesListView::Usage, 10 );
    m_widget->setColumnWidthMode( Smb4KSharesListView::Usage, TQListView::Maximum );
    m_widget->header()->setResizeEnabled( true, Smb4KSharesListView::Usage );
  }
  else
  {
    m_widget->setColumnWidth( Smb4KSharesListView::Usage, 0 );
    m_widget->setColumnWidthMode( Smb4KSharesListView::Usage, TQListView::Manual );
    m_widget->header()->setResizeEnabled( false, Smb4KSharesListView::Usage );
  }

  // Change the text of the share (first column):
  TQListViewItemIterator it( m_widget );
  Smb4KSharesListViewItem *item = NULL;

  while( it.current() )
  {
    item = static_cast<Smb4KSharesListViewItem *>( it.current() );

    if ( item )
    {
      item->setText( 0, (Smb4KSettings::showMountPoint() ?
                        item->shareObject()->path() :
                        item->shareObject()->name()) );
    }

    ++it;
  }

  // Enable/disable support for dropping:
  m_widget->setAcceptDrops( Smb4KSettings::enableDropSupport() );

  // Load or remove all foreign shares. The easiest way to do this
  // is to invoke slotMountedShares():
  slotMountedShares();

  // Adjust the columns:
  for ( int col = 0; col < m_widget->columns(); col++ )
  {
    if ( m_widget->columnWidth( col ) != 0 )
    {
      m_widget->adjustColumn( col );
    }
  }
}


void Smb4KSharesListViewPart::customEvent( TQCustomEvent *e )
{
  switch ( e->type() )
  {
    case EVENT_LOAD_SETTINGS:
    {
      loadSettings();
      slotMountedShares();

      break;
    }
    case EVENT_SET_FOCUS:
    {
      TDEListView *view = static_cast<TDEListView *>( m_widget );

      if ( view->childCount() != 0 )
      {
        view->setSelected( !view->currentItem() ?
                           view->firstChild() :
                           view->currentItem(), true );
      }

      view->setFocus();

      break;
    }
    default:
    {
      break;
    }
  }

  KParts::Part::customEvent( e );
}


/////////////////////////////////////////////////////////////////////////////
// SLOT IMPLEMENTATIONS (Smb4KSharesListViewPart)
/////////////////////////////////////////////////////////////////////////////

void Smb4KSharesListViewPart::slotContextMenuRequested( TQListViewItem *item, const TQPoint &pos, int /*col*/ )
{
  if ( item )
  {
    m_menu->popupMenu()->changeTitle( 0, SmallIcon( "drive-harddisk-mounted" ),
                                      static_cast<Smb4KSharesListViewItem *>( item )->shareObject()->name() );
  }
  else
  {
    m_menu->popupMenu()->changeTitle( 0, SmallIcon( "drive-harddisk-mounted" ), i18n( "Shares" ) );
  }

  m_menu->popupMenu()->exec( pos, 0 );
}


void Smb4KSharesListViewPart::slotSelectionChanged( TQListViewItem *item )
{
  // NOTE: Here we only enable or disable the TDEActions. All other things
  // are done in the Smb4KSharesListView class.

  // This slot is used to enable or disable the actions when the user
  // changes the item in the list view. This slot won't be called when
  // the user clicks on the view port!
  if ( item )
  {
    actionCollection()->action( "unmount_action" )->setEnabled( true );
#ifdef __linux__
    actionCollection()->action( "force_unmount_action" )->setEnabled( Smb4KSettings::useForceUnmount() );
#endif
    actionCollection()->action( "unmount_all_action" )->setEnabled( true );

    Smb4KShare *share = static_cast<Smb4KSharesListViewItem *>( item )->shareObject();

    if ( !share->isBroken() )
    {
      actionCollection()->action( "konsole_action" )->setEnabled( !Smb4KSettings::konsole().isEmpty() );
      actionCollection()->action( "filemanager_action" )->setEnabled( true );
      actionCollection()->action( "synchronize_action" )->setEnabled( !Smb4KSettings::rsync().isEmpty() &&
                                                                      !Smb4KCore::synchronizer()->isRunning() );
    }
    else
    {
      actionCollection()->action( "konsole_action" )->setEnabled( false );
      actionCollection()->action( "filemanager_action" )->setEnabled( false );
      actionCollection()->action( "synchronize_action" )->setEnabled( false );
    }
  }
  else
  {
    // Smb4KSharesListViewPart::slotMouseButtonPressed()
  }
}


void Smb4KSharesListViewPart::slotMouseButtonPressed( TQListViewItem *item )
{
  // NOTE: Here we only enable or disable the TDEActions. All other things
  // are done in the Smb4KSharesListView class.

  // Here we do all the stuff that cannot be done in
  // Smb4KSharesListViewPart::slotSelectionChanged()
  if ( !item )
  {
    actionCollection()->action( "unmount_action" )->setEnabled( false );
#ifdef __linux__
    actionCollection()->action( "force_unmount_action" )->setEnabled( false );
#endif
    actionCollection()->action( "unmount_all_action" )->setEnabled( (m_widget->childCount() > 0) );
    actionCollection()->action( "konsole_action" )->setEnabled( false );
    actionCollection()->action( "filemanager_action" )->setEnabled( false );
    actionCollection()->action( "synchronize_action" )->setEnabled( false );
  }
  else
  {
    // See Smb4KSharesListViewPart::slotSelectionChanged()
  }
}


void Smb4KSharesListViewPart::slotMountedShares()
{
  // Get the list of shares:
  TQValueList<Smb4KShare *> list = Smb4KCore::mounter()->getShares();

  // Update the view:
  if ( !list.isEmpty() )
  {
    // Remove all obsolete items:
    TQListViewItemIterator it( m_widget );
    Smb4KSharesListViewItem *item = NULL;

    while ( it.current() )
    {
      item = static_cast<Smb4KSharesListViewItem *>( it.current() );
      Smb4KShare *share = Smb4KCore::mounter()->findShareByPath( item->shareObject()->path() );

      if( !share || (item->shareObject()->isForeign() && !Smb4KSettings::showAllShares()) )
      {
        delete item;
        item = NULL;
      }

      ++it;
    }

    // Now process the entries in the list:
    bool already_in_view = false;

    for ( TQValueListConstIterator<Smb4KShare *> it = list.begin(); it != list.end(); ++it )
    {
      // Check, whether the share is already in the list. Look for the
      // mount point.
      for ( Smb4KSharesListViewItem *item = static_cast<Smb4KSharesListViewItem *>( m_widget->firstChild() );
            item; item = static_cast<Smb4KSharesListViewItem *>( item->nextSibling() ) )
      {
        if ( TQString::compare( item->shareObject()->path(), (*it)->path() ) == 0 ||
             TQString::compare( item->shareObject()->canonicalPath(), (*it)->canonicalPath() ) == 0 )
        {
          // Replace the share object if something changed:
          if ( !item->sameShareObject( *it ) )
          {
            item->replaceShareObject( *it );
          }

          already_in_view = true;

          break;
        }
        else
        {
          continue;
        }
      }

      if ( !already_in_view )
      {
        if ( !Smb4KSettings::showAllShares() && (*it)->isForeign() )
        {
          // If the user does not want to have foreign shares
          // displayed continue.
          continue;
        }
        else
        {
          // Put the new item into the list view:
          (void) new Smb4KSharesListViewItem( *it, Smb4KSettings::showMountPoint(), m_widget );

          // Adjust the columns:
          for ( int col = 0; col < m_widget->columns(); col++ )
          {
            if ( m_widget->columnWidth( col ) != 0 )
            {
              m_widget->adjustColumn( col );
            }
          }

          continue;
        }
      }

      already_in_view = false;
    }

    m_widget->sort();
  }
  else
  {
    if ( m_widget->childCount() != 0 )
    {
      m_widget->clear();

      // Adjust the columns:
      for ( int col = 0; col < m_widget->columns(); col++ )
      {
        if ( m_widget->columnWidth( col ) != 0 )
        {
          m_widget->adjustColumn( col );
        }
      }
    }
  }

  // Update the tool tip, if it exists:
  if ( m_widget->childCount() != 0 )
  {
    m_widget->updateToolTip();
  }

  // Enable/disable the actions:
  TQListViewItem *item = m_widget->currentItem();
  bool have_selected_item = (item && item->isSelected());

  actionCollection()->action( "unmount_action" )->setEnabled( have_selected_item );
#ifdef __linux__
  if ( Smb4KSettings::useForceUnmount() )
  {
    actionCollection()->action( "force_unmount_action" )->setEnabled( have_selected_item );
  }
  else
  {
    actionCollection()->action( "force_unmount_action" )->setEnabled( false );
  }
#endif
  actionCollection()->action( "unmount_all_action" )->setEnabled( (m_widget->childCount() > 0) );
  actionCollection()->action( "konsole_action" )->setEnabled( !Smb4KSettings::konsole().isEmpty() && have_selected_item );
  actionCollection()->action( "filemanager_action" )->setEnabled( have_selected_item );
  actionCollection()->action( "synchronize_action" )->setEnabled( !Smb4KSettings::rsync().isEmpty() &&
                                                                  !Smb4KCore::synchronizer()->isRunning() &&
                                                                  have_selected_item );
}


void Smb4KSharesListViewPart::slotUnmountShare()
{
  Smb4KSharesListViewItem *item = static_cast<Smb4KSharesListViewItem *>( m_widget->currentItem() );

  if ( item )
  {
    Smb4KCore::mounter()->unmountShare( item->shareObject(), false );
  }
}


void Smb4KSharesListViewPart::slotForceUnmountShare()
{
  Smb4KSharesListViewItem *item = static_cast<Smb4KSharesListViewItem *>( m_widget->currentItem() );

  if ( item )
  {
    Smb4KCore::mounter()->unmountShare( item->shareObject(), true );
  }
}


void Smb4KSharesListViewPart::slotUnmountAllShares()
{
  Smb4KCore::mounter()->unmountAllShares();
}


void Smb4KSharesListViewPart::slotSynchronize()
{
  Smb4KSharesListViewItem *item = static_cast<Smb4KSharesListViewItem *>( m_widget->currentItem() );
  Smb4KSynchronizationDialog *dlg = static_cast<Smb4KSynchronizationDialog *>( m_widget->child( "SynchronizationDialog", "Smb4KSynchronizationDialog", true ) );

  if ( item && !item->shareObject()->isBroken() && !dlg )
  {
    dlg = new Smb4KSynchronizationDialog( item->shareObject(), m_widget, "SynchronizationDialog" );

    dlg->show();
  }
}

void Smb4KSharesListViewPart::slotKonsole()
{
  Smb4KSharesListViewItem *item = static_cast<Smb4KSharesListViewItem *>( m_widget->currentItem() );

  if ( item && !item->shareObject()->isBroken() )
  {
    Smb4KCore::open( item->shareObject(), Smb4KCore::Konsole );
  }
}


void Smb4KSharesListViewPart::slotFilemanager()
{
  Smb4KSharesListViewItem *item = static_cast<Smb4KSharesListViewItem *>( m_widget->currentItem() );

  if ( item && !item->shareObject()->isBroken() )
  {
    Smb4KCore::open( item->shareObject(), Smb4KCore::Konqueror );
  }
}


void Smb4KSharesListViewPart::slotSynchronizationState( int state )
{
  switch ( state )
  {
    case SYNCHRONIZER_START:
    {
      actionCollection()->action( "synchronize_action" )->setEnabled( false );

      break;
    }
    case SYNCHRONIZER_STOP:
    {
      actionCollection()->action( "synchronize_action" )->setEnabled( true );

      break;
    }
    default:
    {
      break;
    }
  }
}



/////////////////////////////////////////////////////////////////////////////
// FACTORY STUFF
/////////////////////////////////////////////////////////////////////////////

Smb4KSharesListViewPartFactory::Smb4KSharesListViewPartFactory()
: KParts::Factory()
{
}


Smb4KSharesListViewPartFactory::~Smb4KSharesListViewPartFactory()
{
  delete m_instance;
  delete m_about;

  m_instance = 0L;
}


KParts::Part *Smb4KSharesListViewPartFactory::createPartObject( TQWidget *parentWidget, const char *widgetName,
TQObject *parent, const char *name, const char *, const TQStringList & )
{
  Smb4KSharesListViewPart *obj = new Smb4KSharesListViewPart( parentWidget, widgetName, parent, name );

  // See if we are to be read-write or not
//   if (TQCString(classname) == "KParts::ReadOnlyPart")
//   {
//     obj->setReadWrite(false);
//   }

  return obj;
}


TDEInstance *Smb4KSharesListViewPartFactory::instance()
{
  if( !m_instance )
  {
    m_about = new TDEAboutData( "smb4kshareslistviewpart", I18N_NOOP( "Smb4KSharesListViewPart" ), "1.0" );
    m_about->addAuthor("Alexander Reinholdt", 0, "dustpuppy@users.berlios.de");
    m_about->setLicense( TDEAboutData::License_GPL );
    m_instance = new TDEInstance( m_about );
  }

  return m_instance;
}


/////////////////////////////////////////////////////////////////////////////
// INIT
/////////////////////////////////////////////////////////////////////////////

extern "C"
{
  TDE_EXPORT void *init_libsmb4kshareslistview()
  {
    TDEGlobal::locale()->insertCatalogue( "smb4k" );
    return new Smb4KSharesListViewPartFactory;
  }
}


#include "smb4kshareslistview_part.moc"
