/***************************************************************************
                          userpicturesdialog.cpp  -  description
                             -------------------
    begin                : Fri Jul 7 2008
    copyright            : (C) 2008 by Antonio Nastasi
    email                : sifcenter@gmail.com
 ***************************************************************************/

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


#include "userpicturesdialog.h"

#include "../utils/kmessconfig.h"
#include "../kmessdebug.h"

#include <QDir>

#include <KMessageBox>



// Constructor
UserPicturesDialog::UserPicturesDialog( QWidget *parent )
  :  KDialog( parent )
{
  // Setup the user interface
  setObjectName( "UserPictures" );
  QWidget *mainWidget = new QWidget( this );
  setupUi( mainWidget );
  setMainWidget( mainWidget );

  setButtons( KDialog::User1 | KDialog::Ok | KDialog::Close );
  setDefaultButton( Ok );

  setButtonText( Ok,    i18n( "&Use" ) );
  setButtonText( User1, i18n( "&Delete" ) );

  setWindowTitle( i18n( "Choose or Remove Your Display Picture" ) );

  // Connect signals
  connect( listPictures_, SIGNAL(     itemSelectionChanged() ),
           this,            SLOT( slotItemSelectionChanged() ) );
}



// Destructor
UserPicturesDialog::~UserPicturesDialog()
{
  clearList();
  kmDebug() << "DESTROYED";
}



// Clear and free memory of list widget
void UserPicturesDialog::clearList()
{
  // Check if it's necessary the cleaning
  if( listPictures_->count() == 0 )
  {
    return;
  }

  // Remove the items
  while( listPictures_->count() != 0 )
  {
    delete listPictures_->takeItem( 0 );
  }
}



// Current item was changed
void UserPicturesDialog::slotItemSelectionChanged()
{
  QListWidgetItem *currentItem = listPictures_->currentItem();
  bool selected = false;

  if( currentItem != 0 )
  {
    // Set current item to avoid lost the blue rect on selection
    listPictures_->setCurrentItem( currentItem );
    selected = true;
  }

  enableButton( Ok,    selected );
  enableButton( User1, selected );
}



// Use the selected picture.
void UserPicturesDialog::usePicture()
{
  // Check if the current item is valid
  const QListWidgetItem *currentItem = listPictures_->currentItem();
  if( currentItem == 0 )
  {
    return;
  }

  emit pictureUpdate( false, currentItem->data( Qt::UserRole ).toString() );
}



// Delete the selected picture.
void UserPicturesDialog::deletePicture()
{
  // Check if the current item is valid
  const QListWidgetItem *currentItem = listPictures_->currentItem();
  if( currentItem == 0 )
  {
    return;
  }

  // Request confirmation
  int result = KMessageBox::questionYesNo( this,
                                           i18n( "Are you sure you want to delete this display picture?",
                                           i18nc( "Dialog box title", "Delete Display Picture" ) ) );
  if( result != KMessageBox::Yes )
  {
    return;
  }

  // Check if the file exists and remove it
  const QString filename( currentItem->data( Qt::UserRole ).toString() );
  if( QFile::exists( filename ) )
  {
    QFile::remove( filename );
  }

  // Update the list
  updateWidgets( handle_ );
}



// Update the widgets
void UserPicturesDialog::updateWidgets( const QString &handle )
{
  int number = 0;
  const QDir dir( KMessConfig::instance()->getAccountDirectory( handle ) + "/displaypics" );
  const QString dirPath( dir.absolutePath() );

  QListWidgetItem *item;

  // Clear the list
  clearList();

  QString path;
  foreach( const QString &file, dir.entryList( QDir::Files | QDir::NoDotAndDotDot ) )
  {
    // To avoid listing of temporary picture file
    if( file.contains( "temporary-picture" ) )
    {
      continue;
    }

    path = dirPath + "/" + file;

    // bug in 4.6.1/4.6.2 - QPixmap doesn't call detach() before load(), so the previous code
    // here caused multiple copies of the last pixmap to be loaded to appear in the list box.
    // workaround. this is fixed in 4.6.3.
    QPixmap icon( path );
    if( ! icon.isNull() )
    {
      item = new QListWidgetItem( icon, QString::number( ++number ), listPictures_ );
      item->setData( Qt::UserRole, path );
    }
  }

  enableButton( Ok,    false );
  enableButton( User1, false );

  handle_ = handle;
}



// A button has been pressed, act accordingly
void UserPicturesDialog::slotButtonClicked( int button )
{
  switch( button )
  {
    case KDialog::Ok:
      usePicture();
      accept();
      break;

    case KDialog::User1:
      deletePicture();
      return;
      break;

    default:
      KDialog::slotButtonClicked( button );
      break;
  }
}



#include "userpicturesdialog.moc"
