/***************************************************************************
                          contactextension.cpp  -  description
                             -------------------
    begin                : Fri 13 Dec 2002
    copyright            : (C) 2003 by Michael Curtis.
    email                : mdcurtis@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 "contactextension.h"

#include "../currentaccount.h"
#include "../kmessdebug.h"

#include <QFile>

#include <KLocale>
#include <KConfigGroup>



// The constructor with specified contact handle
ContactExtension::ContactExtension( Contact *contact )
 : QObject(),
   alternativeName_(),
   alternativePictureFile_(""),
   disableNotifications_(false),
   pictureFile_(""),
   soundFile_(""),
   useAlternativeName_(false)
{
  // Set the current contact and connect the contactOffline event for lastSeen entry
  handle_  = contact->getHandle();
  contact_ = contact;
  connect( contact_ , SIGNAL( contactOffline( Contact*, bool ) ), this, SLOT( setLastSeen() ) );
}


// The destructor
ContactExtension::~ContactExtension()
{
}



// Clear the cache of picture files
void ContactExtension::clearCache()
{
  QFile file;

  // Grep all pictures and remove these
  foreach( const QString &fileName,  pictureFileList_ )
  {
    // Remove the picture file
    file.setFileName( fileName );
    if( file.exists() )
    {
      file.remove();
      file.close();
    }

    // Remove the dat file
    file.setFileName( fileName  + ".dat" );
    if( file.exists() )
    {
      file.remove();
      file.close();
    }
  }
  pictureFileList_.clear();
}



// Read the contact alias
const QString & ContactExtension::getAlternativeName( FormattingMode mode ) const
{
  return alternativeName_.getString( mode );
}



// Read the custom contact picture path
const QString& ContactExtension::getContactAlternativePicturePath() const
{
  return alternativePictureFile_;
}



// Read the original contact picture path
const QString ContactExtension::getContactPicturePath() const
{
  if( QFile::exists( pictureFile_ ) )
  {
    return pictureFile_;
  }

  return QString::null;
}



// Read the custom contact sound path
const QString ContactExtension::getContactSoundPath() const
{
  if( QFile::exists( soundFile_ ) )
  {
    return soundFile_;
  }

  return QString::null;
}



// Read whether KMess should notify when this contact does an action
bool ContactExtension::getDisableNotifications() const
{
  return disableNotifications_;
}



// Read when the contact has been seen the last time
const QDateTime& ContactExtension::getLastSeen()
{
  return lastSeen_;
}


// Read when the last message from this contact has been received
const QDateTime& ContactExtension::getLastMessageDate()
{
  return lastMessageDate_;
}



// Get the notes about this contact
const QString& ContactExtension::getNotes() const
{
  return notes_;
}



// Read whether to use the alias or not
bool ContactExtension::getUseAlternativeName() const
{
  return useAlternativeName_;
}



// Read the list of pictures which the contact has used
const QStringList& ContactExtension::getPictureList() const
{
  return pictureFileList_;
}



// Load extension settings for a contact
void ContactExtension::readProperties( const KConfigGroup &config )
{
  // Get the configuration group where this contact's data is stored
  const KConfigGroup& extensionGroup( config.group( "Extension" ) );

  // When changing any of those default values, also change the saving condition
  // in saveProperties() !
  alternativeName_                        = extensionGroup.readEntry("alternativeName",          ""            );
  alternativePictureFile_                 = extensionGroup.readEntry("alternativePictureFile",   ""            );
  lastSeen_        = QDateTime::fromTime_t( extensionGroup.readEntry("lastSeen",                 0             ) );
  lastMessageDate_ = QDateTime::fromTime_t( extensionGroup.readEntry("lastMessageDate",          0             ) );
  disableNotifications_                   = extensionGroup.readEntry("disableNotifications",     false         );
  notes_                                  = extensionGroup.readEntry("notes",                    ""            );
  pictureFile_                            = extensionGroup.readEntry("pictureFile",              ""            );
  pictureFileList_                        = extensionGroup.readEntry("pictureFileList",          QStringList() );
  soundFile_                              = extensionGroup.readEntry("soundFile",                ""            );

  // We use the accessor function here because it handles the update, if required
  setUseAlternativeName  ( extensionGroup.readEntry("useAlternativeName",       false       ) );
}



// Save extension settings for a contact
void ContactExtension::saveProperties( KConfigGroup &config )
{
  // Get the configuration group where this contact's data is stored
  KConfigGroup extensionGroup( config.group( "Extension" ) );

  // If no info have been changed, don't waste space writing it, and if it's present already, remove the group.
  if(  ! useAlternativeName_
      && disableNotifications_
      && alternativeName_.getOriginal().isEmpty()
      && alternativePictureFile_       .isEmpty()
      && lastSeen_                     .isNull()
      && lastMessageDate_              .isNull()
      && pictureFile_                  .isEmpty()
      && soundFile_                    .isEmpty() )
  {
#ifdef KMESSDEBUG_CONTACTEXTENSION
    if( extensionGroup.hasGroup( "Extension" ) )
    {
      kDebug() << "Deleting unused contact info for" << handle_;
    }
    else
    {
      kDebug() << "Not saving unused contact info for" << handle_;
    }
#endif

    config.deleteGroup( "Extension" );
    return;
  }

  extensionGroup.writeEntry( "useAlternativeName",     useAlternativeName_            );
  extensionGroup.writeEntry( "alternativePictureFile", alternativePictureFile_        );
  extensionGroup.writeEntry( "alternativeName",        alternativeName_.getOriginal() );
  extensionGroup.writeEntry( "disableNotifications",   disableNotifications_          );
  extensionGroup.writeEntry( "notes",                  notes_                         );

  // If the contact is connects, refresh the lastSeen before saves it
  if( contact_->isOnline() )
  {
    setLastSeen();
  }

  if( ! lastSeen_.isNull() && lastSeen_.isValid() )
  {
    extensionGroup.writeEntry( "lastSeen",           lastSeen_.toTime_t()        );
  }
  
  if( ! lastMessageDate_.isNull() && lastMessageDate_.isValid() )
  {
    extensionGroup.writeEntry( "lastMessageDate",    lastMessageDate_.toTime_t() );
  }
  
  extensionGroup.writeEntry( "pictureFile",        pictureFile_                );
  extensionGroup.writeEntry( "pictureFileList",    pictureFileList_            );
  extensionGroup.writeEntry( "soundFile",          soundFile_                  );
}



// Change the contact alias
void ContactExtension::setAlternativeName( const QString& newAlternativeName )
{
  // Ignore invalid requests
  if( newAlternativeName.isEmpty() || newAlternativeName == alternativeName_.getOriginal() )
  {
    return;
  }

  // Copy the new name to the three versions
  alternativeName_.setString( newAlternativeName );

  if( getUseAlternativeName() )
  {
    emit changedFriendlyName();
  }
}



// Change the custom contact picture path
void ContactExtension::setContactAlternativePicturePath( const QString& _newVal )
{
  alternativePictureFile_ = _newVal;
  
  emit changedPicture();
}



// Change the original contact picture path
void ContactExtension::setContactPicturePath( const QString & _newVal )
{
  pictureFile_ = _newVal;

  if( ! _newVal.isEmpty()  )
  {
    // If the current picture isn't in the list of all used pictures,
    // then add it.
    if( ! pictureFileList_.contains( _newVal ) )
    {
      pictureFileList_.append( _newVal );
    }

    // If the picture file hasn't a dat file, then create it
    // and put into the current date
    QFile fileDat( _newVal + ".dat" );
    if( ! fileDat.exists () )
    {
      if ( fileDat.open( QIODevice::WriteOnly | QIODevice::Text ) )
      {
        QTextStream out( &fileDat );
        out << QDate::currentDate ().toString( Qt::SystemLocaleDate );
        fileDat.close();
      }
    }
  }

  emit changedPicture();
}



// Change the custom contact sound path
void ContactExtension::setContactSoundPath( const QString & _newVal)
{
  soundFile_ = _newVal;
}



// Write whether KMess should notify when this contact change status or do any actions
void ContactExtension::setDisableNotifications( bool _newVal )
{
  disableNotifications_ = _newVal;
}



// Set when the contact has been seen the last time
void ContactExtension::setLastSeen()
{
  lastSeen_ = QDateTime::currentDateTime();
}



// Set the time of the last received message from this contact
void ContactExtension::setLastMessageDate()
{
  lastMessageDate_ = QDateTime::currentDateTime();
}



// Write the notes about this contact
void ContactExtension::setNotes( const QString& _newVal )
{
  notes_ = _newVal;
}



// Set whether to use the alias or not
void ContactExtension::setUseAlternativeName( bool _newVal)
{
  bool needUpdate;

  needUpdate = ( useAlternativeName_ != _newVal);

  useAlternativeName_ = _newVal;

  if ( needUpdate == true ) emit changedFriendlyName();
}



#include "contactextension.moc"
