/***************************************************************************
    smb4kpreviewdialog.cpp  -  The preview dialog of Smb4K
                             -------------------
    begin                : Fre Jul 4 2003
    copyright            : (C) 2003-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 <tqlayout.h>
#include <tqtooltip.h>
#include <tqiconset.h>

// KDE includes
#include <tdelocale.h>
#include <tdeapplication.h>
#include <kiconloader.h>
#include <kdebug.h>
#include <tdetoolbarbutton.h>

// application specific includes
#include "smb4kpreviewdialog.h"
#include "../core/smb4kcore.h"
#include "../core/smb4knetworkitems.h"
#include "../core/smb4ksettings.h"


Smb4KPreviewDialog::Smb4KPreviewDialog( Smb4KShareItem *item, TQWidget *parent, const char *name )
: KDialogBase( Plain, i18n( "Preview" ), Close, Close, parent, name, false, true )
{
  setWFlags( TQt::WDestructiveClose );

  m_item = new Smb4KPreviewItem( item );

  if ( m_item )
  {
    if ( Smb4KHostItem *host = Smb4KCore::scanner()->getHost( item->host(), item->workgroup() ) )
    {
      m_item->setIP( host->ip() );
    }

    m_button_id = None;

    m_current_item = m_history.end();

    setupView();

    setInitialSize( configDialogSize( *(Smb4KSettings::self()->config()), "PreviewDialog" ) );

    connect( m_view,                 TQT_SIGNAL( executed( TQIconViewItem * ) ),
            this,                    TQT_SLOT( slotItemExecuted( TQIconViewItem * ) ) );

    connect( m_toolbar,              TQT_SIGNAL( clicked( int ) ),
            this,                    TQT_SLOT( slotButtonClicked( int ) ) );

    connect( m_combo,                TQT_SIGNAL( activated( const TQString & ) ),
            this,                    TQT_SLOT( slotItemActivated( const TQString & ) ) );

    connect( Smb4KCore::previewer(), TQT_SIGNAL( result( Smb4KPreviewItem * ) ),
             this,                   TQT_SLOT( slotReceivedData( Smb4KPreviewItem * ) ) );

    m_initialized = Smb4KCore::previewer()->preview( m_item );
  }

  setMinimumSize( (sizeHint().width() > 350 ? sizeHint().width() : 350), sizeHint().height() );
}


Smb4KPreviewDialog::~Smb4KPreviewDialog()
{
  delete m_item;
}


void Smb4KPreviewDialog::setupView()
{
  TQFrame *frame = plainPage();
  TQGridLayout *layout = new TQGridLayout( frame );

  m_view = new TDEIconView( frame, 0, 0 );
  m_view->setItemTextPos( TDEIconView::Right );
  m_view->setResizeMode( TDEIconView::Adjust );
  m_view->setArrangement( TDEIconView::TopToBottom );
  m_view->setSpacing( 1 );
  m_view->setGridX( 200 );
  m_view->setWordWrapIconText( false );
  m_view->setShowToolTips( true );
  m_view->setAutoArrange( true );
  m_view->setSorting( true, true );

  m_toolbar = new TDEToolBar( frame, 0, true, false );
  m_toolbar->insertButton( "reload", Reload, true, i18n( "Reload" ), 0 );
  m_toolbar->insertButton( "back", Back, false, i18n( "Back" ), 1 );
  m_toolbar->insertButton( "forward", Forward, false, i18n( "Forward" ), 2 );
  m_toolbar->insertButton( "go-up", Up, false, i18n( "Up" ), 3 );

  m_combo = new KComboBox( false, m_toolbar, 0 );
  m_combo->listBox()->setHScrollBarMode( TQScrollView::Auto );
  m_combo->listBox()->setVScrollBarMode( TQScrollView::Auto );
  m_combo->listBox()->setMinimumHeight( 100 );
  m_toolbar->insertWidget( Combo, 10, m_combo, 4 );
  m_toolbar->setItemAutoSized( Combo, true );

  layout->addWidget( m_view, 0, 0, 0 );
  layout->addWidget( m_toolbar, 1, 0, 0 );
}


/////////////////////////////////////////////////////////////////////////////
// TQT_SLOT IMPLEMENTATIONS
/////////////////////////////////////////////////////////////////////////////

void Smb4KPreviewDialog::slotReceivedData( Smb4KPreviewItem *item )
{
  // If the item is NULL or not equal to m_item,
  // stop right here:
  if ( !item || item != m_item )
  {
    return;
  }

  // Clear the icon view:
  m_view->clear();

  // The item should be equal to m_item, so we can use either of those
  // pointers.

  // Process the data:
  if ( !item->contents().isEmpty() )
  {
    // Generate the history.
    switch ( m_button_id )
    {
      case Reload: /* Really? */
      case Back:
      case Forward:
      {
        // Do not insert anything into the history if
        // one of these three buttons was clicked.

        break;
      }
      default:
      {
        m_history.append( item->location() );
        m_current_item = --m_history.end();

        break;
      }
    }

    // Clear the combo box, put the new history there and set the
    // current item:
    m_combo->clear();

    for ( TQStringList::Iterator it = m_history.begin(); it != m_history.end(); it++ )
    {
      if ( !m_combo->listBox()->findItem( *it, TQt::CaseSensitive|TQt::ExactMatch ) )
      {
        m_combo->insertItem( *it, -1 );
      }
    }

    m_combo->setCurrentText( *m_current_item );

    // Now put the contents in the icon view:
    for ( TQValueList<ContentsItem>::ConstIterator it = item->contents().begin();
          it != item->contents().end(); ++it )
    {
      switch ( (*it).first )
      {
        case Smb4KPreviewItem::File:
        {
          TDEIconViewItem *view_item = new TDEIconViewItem( m_view, (*it).second, SmallIcon( "file" ) );
          view_item->setKey( TQString( "[file]_%1" ).arg( (*it).second ) );

          break;
        }
        case Smb4KPreviewItem::Directory:
        {
          // We do not want to show the '.' and '..' directories.
          if ( TQString::compare( (*it).second, "." ) != 0 && TQString::compare( (*it).second, ".." ) != 0 )
          {
            TDEIconViewItem *view_item = new TDEIconViewItem( m_view, (*it).second, SmallIcon( "folder" ) );
            view_item->setKey( TQString( "[directory]_%1" ).arg( (*it).second ) );
          }

          break;
        }
        case Smb4KPreviewItem::HiddenFile:
        {
          if ( Smb4KSettings::previewHiddenItems() )
          {
            TDEIconViewItem *view_item = new TDEIconViewItem( m_view, (*it).second, SmallIcon( "file" ) );
            view_item->setKey( TQString( "[file]_%1" ).arg( (*it).second ) );
          }

          break;
        }
        case Smb4KPreviewItem::HiddenDirectory:
        {
          if ( Smb4KSettings::previewHiddenItems() &&
               TQString::compare( (*it).second, "." ) != 0 && TQString::compare( (*it).second, ".." ) != 0 )
          {
            TDEIconViewItem *view_item = new TDEIconViewItem( m_view, (*it).second, SmallIcon( "folder" ) );
            view_item->setKey( TQString( "[directory]_%1" ).arg( (*it).second ) );
          }

          break;
        }
        default:
        {
          break;
        }
      }
    }

    // Now activate or deactivate the buttons:

    // Activate the 'Up' button if the current address is
    // not equal to the base address.
    m_toolbar->setItemEnabled( Up, TQString::compare( "//"+item->host()+"/"+item->share()+"/", item->location() ) != 0 );

    // Activate/Deactivate 'Back' and 'Forward' buttons.
    m_toolbar->setItemEnabled( Back, m_current_item != m_history.at( 0 ) );
    m_toolbar->setItemEnabled( Forward, m_current_item != m_history.at( m_history.count() - 1 ) );
  }
  else
  {
    return;
  }
}


void Smb4KPreviewDialog::slotItemExecuted( TQIconViewItem *item )
{
  if ( !item->key().startsWith( "[file]_" ) )
  {
    m_button_id = None;

    m_item->setPath( m_item->path()+item->text()+"/" );

    Smb4KCore::previewer()->preview( m_item );
  }
}


void Smb4KPreviewDialog::slotButtonClicked( int id )
{
  m_button_id = id;

  m_item->clearContents();

  switch ( id )
  {
    case Reload:
    {
      Smb4KCore::previewer()->preview( m_item );

      break;
    }
    case Up:
    {
      // Do nothing if the path is empty because
      // we are already in the root directory.
      if ( m_item->path().isEmpty() )
      {
        return;
      }

      if ( m_item->path().contains( "/" ) > 1 )
      {
        m_item->setPath( m_item->path().section( "/", 0, -3 ).append( "/" ) );
      }
      else if ( m_item->path().contains( "/", true ) == 1 )
      {
        m_item->setPath( TQString() );
      }

      Smb4KCore::previewer()->preview( m_item );

      break;
    }
    case Back:
    {
      // Move one item back in the list:
      if ( m_current_item != m_history.at( 0 ) )
      {
        m_current_item--;
      }
      else
      {
        return;
      }

      // Get the path:
      if ( (*m_current_item).contains( "/", true ) == 3 )
      {
        m_item->setPath( TQString() );
      }
      else
      {
        m_item->setPath( (*m_current_item).section( "/", 4, -1 ) );

        if ( !m_item->path().isEmpty() )
        {
          m_item->setPath( m_item->path()+"/" );
        }
        else
        {
          // Do nothing.
        }
      }

      Smb4KCore::previewer()->preview( m_item );

      break;
    }
    case Forward:
    {
      // Move one item forward in the list:
      if ( m_current_item != m_history.at( m_history.count() - 1 ) )
      {
        m_current_item++;
      }
      else
      {
        return;
      }

      // Get the path:
      if ( (*m_current_item).contains( "/", true ) == 3 )
      {
        m_item->setPath( TQString() );
      }
      else
      {
        m_item->setPath( (*m_current_item).section( "/", 4, -1 ) );

        if ( !m_item->path().isEmpty() )
        {
          m_item->setPath( m_item->path()+"/" );
        }
        else
        {
          // Do nothing.
        }
      }

      Smb4KCore::previewer()->preview( m_item );

      break;
    }
    default:
    {
      break;
    }
  }
}


void Smb4KPreviewDialog::slotItemActivated( const TQString &item )
{
  m_button_id = Combo;

  // First we have to strip the address:
  m_item->setPath( item.section( "//"+m_item->host()+"/"+m_item->share()+"/", 1, 1 ).stripWhiteSpace() );

  Smb4KCore::previewer()->preview( m_item );
}


void Smb4KPreviewDialog::slotClose()
{
  saveDialogSize( *(Smb4KSettings::self()->config()), "PreviewDialog" );

  KDialogBase::slotClose();
}


#include "smb4kpreviewdialog.moc"

