/***************************************************************************
                          imagewidget.cpp  -  description
                             -------------------
    begin                : 03-08-2004
    copyright            : (C) 2004 by Madelman
    email                : madelman@users.sourceforge.net
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   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 "imagewidget.h"

#include <qwidget.h>
#include <qcheckbox.h>
#include <qpixmap.h>
#include <qfileinfo.h>
#include <qfile.h>
#include <qimage.h>
#include <qlabel.h>

#include <klistbox.h>
#include <kpushbutton.h>

#include <kio/netaccess.h>
#include <klocale.h>
#include <kmdcodec.h>
#include <kstandarddirs.h>
#include <kfiledialog.h>

#include <kmessagebox.h>
#include <kdebug.h>
#include <kdeversion.h>



/**
 * Constructor
 */
ImageWidget::ImageWidget( QWidget* parent,  const char* name, WFlags fl )
: ImageWidgetInterface( parent, name, fl ),
  hasTempImage_(false)
{

  // Find the default image
  KStandardDirs *dirs   = KGlobal::dirs();
  QString defaultImage  = dirs->findResource( "data", "kmess/pics/kmesspic.png"  );

  // Load the image in the X-Server:
  defaultPixmap_ = QPixmap(defaultImage);
  customPixmap_  = defaultPixmap_;
}



/**
 * Destructor
 */
ImageWidget::~ImageWidget()
{
  // Clean up the temp file.
  if(hasTempImage_)
  {
    QFile::remove(tempImageFile_);
  }

  // no need to delete child widgets, Qt does it all for us
}



/**
 * Load the dialog settings.
 */
void ImageWidget::loadSettings(Account *account)
{
  bool showImage;
  bool useCustom;

  myHandle_      = account->getHandle();
  imageFile_     = account->getImagePath();
  tempImageFile_ = account->getCustomImagePath() + ".tmp";

  showImage      = account->getShowImage();
  useCustom      = account->getCustomImage();


  // Load the custom pixmap if we have one.
  if( showImage && useCustom )
  {
    customPixmap_ = QPixmap( imageFile_ );

    if(customPixmap_.isNull())
    {
      // Failed to load
      useCustom = false;
      customPixmap_ = defaultPixmap_;
    }
  }

  // Set the "Show Image" and "Use default" checkbox
  showImageCheckBox_->setChecked( showImage );
  useDefaultCheckBox_->setChecked( ! useCustom);

  // Run the event manually this time to update the GUI.
  showImageToggled( showImage );
  useDefaultToggled( ! useCustom );
}



/**
 * Save the settings in the account object.
 */
void ImageWidget::saveSettings( Account *account)
{
  QString   imageName     = 0;
  QString   tempImageName = 0;
  QDir      imageFolder;
  bool      showImage;
  bool      useDefault;
  bool      success;

  showImage  = showImageCheckBox_->isChecked();
  useDefault = useDefaultCheckBox_->isChecked();

  // Update the settings
  account->setShowImage( showImage );
  account->setCustomImage( ! useDefault );

  // Update the picture if we have one.
  if(hasTempImage_)
  {
    if(useDefault || ! showImage)
    {
      // The temporary file is no longer needed.
      QFile::remove(tempImageFile_);
      hasTempImage_ = false;
    }
    else
    {
      imageName = account->getCustomImagePath();

      // Rename the temp file, place it over the new file
      imageFolder = QDir( QFileInfo(imageName).dir() );
      success = imageFolder.rename( tempImageFile_, imageName );
      hasTempImage_ = false;

      if( ! success)
      {
        kdDebug() << "WARNING - The display picture file could not be renamed." << endl;
      }
    }
  }

  // Create the MSN Object again.
  account->updateMsnObject();
}



/*
 * Allow the user to select an image, and convert it to 96x96, place it in a temp file.
 */
void ImageWidget::selectImage()
{
  // This code is partially borrowed from Kopete.

  KStandardDirs *dirs   = KGlobal::dirs();
  bool    isRemoteFile  = false;
  QString safeHandle    = 0;
  KURL    filePath      = 0;
  QString localFilePath = 0;
  QString tempImageName = 0;
  QImage  imageData     = 0;
  QString startDir      = dirs->findResource("data", "kdm/pics/users/");

  // Show the open file dialog
  filePath = KFileDialog::getImageOpenURL( startDir, this, i18n( "Display Picture" ) );
  if(filePath.isEmpty())
  {
    return;
  }

  // Read the path.
  if(filePath.isLocalFile())
  {
    localFilePath = filePath.path();
  }
  else
  {
    // File is remote, download it to a local folder
    // first because QPixmap doesn't have KIO magic.
    // KIO::NetAccess::download fills the localFilePath field.
#if KDE_IS_VERSION(3,2,0)
    if(! KIO::NetAccess::download(filePath, localFilePath, this ))
#else
    if(! KIO::NetAccess::download(filePath, localFilePath ))
#endif
    {
      KMessageBox::sorry(this, i18n("Downloading of display image failed"), i18n("KMess"));
      return;
    }

    isRemoteFile = true;
  }


  // Convert the image to the correct format.
  // We use a temporary filename first and replace the original if you press OK.
  imageData = QImage(localFilePath);  // Load image data
  imageData = imageData.smoothScale(96, 96, QImage::ScaleMax); // Makes smallest edge 96 pixels, preserving aspect ratio

  if(! imageData.isNull() && (imageData.width() != 96 || imageData.height() != 96))
  {
    // Copy the middle part of the image.
    imageData = imageData.copy( (imageData.width() - 96) / 2,  // X
                                (imageData.height() - 96) / 2, // Y
                                96, 96 );
  }


  if(! imageData.isNull() && imageData.save(tempImageFile_, "PNG") )
  {
    // Sucess! Update the preview image
    customPixmap_ = QPixmap(tempImageFile_);
    pictureLabel_->setPixmap(customPixmap_);

    useDefaultCheckBox_->setChecked(false);
    hasTempImage_ = true;
  }
  else
  {
    KMessageBox::sorry( this,
                        i18n( "An error occurred when trying to change the display picture.\n"
                              "Make sure that you have selected a correct image file" ),
                        i18n( "KMess" ) );
  }

  // Remove any temporary files
  if(isRemoteFile)
  {
    KIO::NetAccess::removeTempFile(localFilePath);
  }
}



// Slot running when the "Show image" checkbox was toggled.
void ImageWidget::showImageToggled(bool showImage)
{
  useDefaultCheckBox_ -> setEnabled( showImage );
  browseButton_       -> setEnabled( showImage );
  pictureLabel_       -> setEnabled( showImage );
}



// Slot running when the "Use default" checkbox was toggled.
void ImageWidget::useDefaultToggled(bool useDefault)
{
  if(useDefault)
  {
    pictureLabel_->setPixmap( defaultPixmap_ );
  }
  else
  {
    pictureLabel_->setPixmap( customPixmap_ );
  }
}


#include "imagewidget.moc"
