/***************************************************************************
    smb4ksharesview_part  -  This Part includes the shares icon view
    of Smb4K.
                             -------------------
    begin                : Mo Dez 4 2006
    copyright            : (C) 2006 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                                                    *
 ***************************************************************************/

// 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 "smb4ksharesiconview_part.h"
#include "smb4ksharesiconview.h"
#include "smb4ksharesiconviewitem.h"
#include "../dialogs/smb4ksynchronizationdialog.h"
#include "../core/smb4kshare.h"
#include "../core/smb4kcore.h"
#include "../core/smb4ksettings.h"


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


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

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

  // Set the widget of this part:
  m_widget = new Smb4KSharesIconView( 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(),      TQT_SIGNAL( updated() ),
           this,                      TQT_SLOT( slotMountedShares() ) );

  connect( Smb4KCore::synchronizer(), TQT_SIGNAL( state( int ) ),
           this,                      TQT_SLOT( slotSynchronizationState( int ) ) );

  connect( m_widget,                  TQT_SIGNAL( contextMenuRequested( TQIconViewItem *, const TQPoint & ) ),
           this,                      TQT_SLOT( slotContextMenuRequested( TQIconViewItem *, const TQPoint & ) ) );

  connect( m_widget,                  TQT_SIGNAL( selectionChanged( TQIconViewItem * ) ),
           this,                      TQT_SLOT( slotSelectionChanged( TQIconViewItem * ) ) );

  connect( m_widget,                  TQT_SIGNAL( pressed( TQIconViewItem * ) ),
           this,                      TQT_SLOT( slotMouseButtonPressed( TQIconViewItem * ) ) );

  connect( m_widget,                  TQT_SIGNAL( executed( TQIconViewItem * ) ),
           this,                      TQT_SLOT( slotFilemanager() ) );
}


Smb4KSharesIconViewPart::~Smb4KSharesIconViewPart()
{
}


void Smb4KSharesIconViewPart::setupActions()
{
  // Create the actions:
  TDEAction *unmount =   new TDEAction( i18n( "&Unmount" ), "drive-harddisk-unmounted", TDEShortcut( CTRL+Key_U ),
                                    this, TQT_SLOT( slotUnmountShare() ),
                                    actionCollection(), "unmount_action" );
#ifdef __linux__
  TDEAction *force =     new TDEAction( i18n( "&Force Unmounting" ), "drive-harddisk-unmounted", TDEShortcut( CTRL+Key_F ),
                                    this, TQT_SLOT( slotForceUnmountShare() ),
                                    actionCollection(), "force_unmount_action" );
#endif
  TDEAction *all =       new TDEAction( i18n( "U&nmount All" ), "gear", TDEShortcut( CTRL+Key_N ),
                                    this, TQT_SLOT( slotUnmountAllShares() ),
                                    actionCollection(), "unmount_all_action" );
  TDEAction *sync =      new TDEAction( i18n( "S&ynchronize" ), "go-bottom", TDEShortcut( CTRL+Key_Y ),
                                    this, TQT_SLOT( slotSynchronize() ),
                                    actionCollection(), "synchronize_action" );
  TDEAction *konsole =   new TDEAction( i18n( "Open with Konso&le" ), "terminal", TDEShortcut( CTRL+Key_L ),
                                    this, TQT_SLOT( slotKonsole() ),
                                    actionCollection(), "konsole_action" );
  TDEAction *konq =      new TDEAction( i18n( "Open with &Konqueror" ), "kfm_home", TDEShortcut( CTRL+Key_K ),
                                    this, TQT_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, "SharesIconViewMenu" );
  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 Smb4KSharesIconViewPart::loadSettings()
{
#ifdef __linux__
  actionCollection()->action( "force_unmount_action" )->setEnabled( Smb4KSettings::useForceUnmount() );
#endif

  // Change the text of the share:
  for ( TQIconViewItem *it = m_widget->firstItem(); it; it = it->nextItem() )
  {
    Smb4KSharesIconViewItem *item = static_cast<Smb4KSharesIconViewItem *>( it );

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

  // 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();
}


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

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

      if ( view->count() != 0 )
      {
        view->setSelected( !view->currentItem() ?
                           view->firstItem() :
                           view->currentItem(), true, false );
      }

      view->setFocus();

      break;
    }
    default:
    {
      break;
    }
  }

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


/////////////////////////////////////////////////////////////////////////////
// TQT_SLOT IMPLEMENTATIONS (Smb4KSharesIconViewPart)
/////////////////////////////////////////////////////////////////////////////

void Smb4KSharesIconViewPart::slotContextMenuRequested( TQIconViewItem *item, const TQPoint &pos )
{
  if ( item )
  {
    m_menu->popupMenu()->changeTitle( 0, SmallIcon( "drive-harddisk-mounted" ),
                                      static_cast<Smb4KSharesIconViewItem *>( item )->shareObject()->name() );
  }
  else
  {
    m_menu->popupMenu()->changeTitle( 0, SmallIcon( "drive-harddisk-mounted" ), i18n( "Shares" ) );
  }

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


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

  // This slot is used to enable or disable the actions when the user
  // changes the item in the icon 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<Smb4KSharesIconViewItem *>( 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
  {
    // Smb4KSharesIconViewPart::slotMouseButtonPressed()
  }
}


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

  // Here we do all the stuff that cannot be done in
  // Smb4KSharesIconViewPart::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->count() > 0) );
    actionCollection()->action( "konsole_action" )->setEnabled( false );
    actionCollection()->action( "filemanager_action" )->setEnabled( false );
    actionCollection()->action( "synchronize_action" )->setEnabled( false );
  }
  else
  {
    // See Smb4KSharesIconViewPart::slotSelectionChanged()
  }
}


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

  // Update the view:
  if ( !list.isEmpty() )
  {
    // Remove all obsolete items:
    Smb4KSharesIconViewItem *test_item = static_cast<Smb4KSharesIconViewItem *>( m_widget->firstItem() );
    Smb4KSharesIconViewItem *next_item = NULL;

    while ( test_item )
    {
      Smb4KShare *share = Smb4KCore::mounter()->findShareByPath( test_item->shareObject()->path() );
      next_item = static_cast<Smb4KSharesIconViewItem *>( test_item->nextItem() );

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

      test_item = next_item;
    }

    // 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 ( Smb4KSharesIconViewItem *item = static_cast<Smb4KSharesIconViewItem *>( m_widget->firstItem() );
            item; item = static_cast<Smb4KSharesIconViewItem *>( item->nextItem() ) )
      {
        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 icon view:
          (void) new Smb4KSharesIconViewItem( *it, Smb4KSettings::showMountPoint(), m_widget );

          continue;
        }
      }

      already_in_view = false;
    }

    m_widget->sort( m_widget->sortDirection() );
  }
  else
  {
    m_widget->clear();
  }

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

  // Enable/disable the actions:
  TQIconViewItem *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->count() > 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 Smb4KSharesIconViewPart::slotUnmountShare()
{
  Smb4KSharesIconViewItem *item = static_cast<Smb4KSharesIconViewItem *>( m_widget->currentItem() );

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


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

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


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


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

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

    dlg->show();
  }
}

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

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


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

  if ( item )
  {
    // Workaround: The item is not selected if you execute it, so
    // we have to do it here:
//     item->setSelected( true );

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


void Smb4KSharesIconViewPart::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
/////////////////////////////////////////////////////////////////////////////

Smb4KSharesIconViewPartFactory::Smb4KSharesIconViewPartFactory()
: KParts::Factory()
{
}


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

  m_instance = 0L;
}


KParts::Part *Smb4KSharesIconViewPartFactory::createPartObject( TQWidget *parentWidget, const char *widgetName,
TQObject *parent, const char *name, const char *, const TQStringList & )
{
  Smb4KSharesIconViewPart *obj = new Smb4KSharesIconViewPart( 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 *Smb4KSharesIconViewPartFactory::instance()
{
  if( !m_instance )
  {
    m_about = new TDEAboutData( "smb4ksharesiconviewpart", I18N_NOOP( "Smb4KSharesIconViewPart" ), "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"
{
  KDE_EXPORT void *init_libsmb4ksharesiconview()
  {
    TDEGlobal::locale()->insertCatalogue( "smb4k" );
    return new Smb4KSharesIconViewPartFactory;
  }
}


#include "smb4ksharesiconview_part.moc"
