/***************************************************************************
                          contactframe.cpp  -  description
                             -------------------
    begin                : Thu Jan 16 2003
    copyright            : (C) 2003 by Mike K. Bennett
    email                : mkb137b@hotmail.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 "contactframe.h"

#include <qdatetime.h>
#include <qlabel.h>
#include <qlayout.h>
#include <qpixmap.h>
#include <qpushbutton.h>
#include <qtoolbutton.h>
#include <qtooltip.h>

#include <kdebug.h>
#include <kglobal.h>
#include <kiconeffect.h>
#include <kiconloader.h>
#include <klocale.h>
#include <krun.h>
#include <kstddirs.h>
#include <kurl.h>

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

// The constructor
ContactFrame::ContactFrame(QWidget *parent, const char *name )
 : ContactFrameInterface(parent,name),
   activated_(false),
   contact_(0)
{
  KIconLoader   *loader = KGlobal::iconLoader();
  KStandardDirs *dirs   = KGlobal::dirs();
  QPixmap        pixmap;
  QString        path;
  // Just for show
  path = dirs->findResource( "data", "kmess/pics/unknown.png" );
  pixmap.load( path );
  contactPixmapLabel_->setPixmap( pixmap );
  // Get the profile pixmap
  profileButton_->setPixmap( loader->loadIcon("kmess", KIcon::Desktop, KIcon::SizeLarge) );
  // Get the email pixmap
  emailButton_->setPixmap( loader->loadIcon("email", KIcon::Desktop, KIcon::SizeLarge) );
 
  //hide();
  // Get the current account
  currentAccount_ = CurrentAccount::instance();
  // Connect up the typing timer
  connect( &typingTimer_,  SIGNAL(     timeout() ),
           this,           SLOT  (  stopTyping() ) );
  // Connect the buttons
  connect( emailButton_,   SIGNAL(     clicked() ),
           this,           SLOT  (   sendEmail() ) );
  connect( profileButton_, SIGNAL(     clicked() ),
           this,           SLOT  ( showProfile() ) );

}



ContactFrame::~ContactFrame()
{
}



// Activate the frame by giving it a contact
void ContactFrame::activate(ContactBase *contact)
{
  if ( contact_ != 0 )
  {
    kdDebug() << "ContactFrame already has a contact." << endl;
    return;
  }
  contact_ = contact;
  // Connect up the contact to update the frame on name, status, and picture changes
  connect( contact_, SIGNAL( changedFriendlyName() ),
           this,     SLOT  ( updateStatusWidgets() ) );
  connect( contact_, SIGNAL(       changedStatus() ),
           this,     SLOT  ( updateStatusWidgets() ) );
  connect( contact_, SIGNAL(      changedPicture() ),
           this,     SLOT  (       updatePicture() ) );


  activated_ = true;
  show();
  // Update the widget based on the contact's settings
  updateWidgets();
}



// Deactivate (grey-out) the frame when a contact leaves the chat
void ContactFrame::deactivate()
{
  enableWidgets( false );
}



// Set whether or not the widgets are enabled or disabled
void ContactFrame::enableWidgets(bool doEnable)
{
  contactPixmapLabel_->setEnabled( doEnable );
  handleLabel_       ->setEnabled( doEnable );
  statusPixmapLabel_ ->setEnabled( doEnable );
  statusLabel_       ->setEnabled( doEnable );
  emailButton_       ->setEnabled( doEnable );
  profileButton_     ->setEnabled( doEnable );
  messageTimeLabel_  ->setEnabled( doEnable );
}



// Return the handle of this frame's contact
QString ContactFrame::getHandle() const
{
  if ( contact_ == 0 )
  {
    return "";
  }
  else
  {
    return contact_->getHandle();
  }
}



// Whether or not the frame has been activated
bool ContactFrame::isActivated() const
{
  return activated_;
}



// The user received a message from this contact
void ContactFrame::messageReceived()
{
  // Get the time and update the time label
	QString time = KGlobal::locale()->formatTime( QTime::currentTime(), true );
  messageTimeLabel_->setText( time );
  // Stop the "user is typing" glow
  typingTimer_.stop();
  stopTyping();

}



// Reactivate the frame when a contact rejoins the chat
void ContactFrame::reactivate()
{
  enableWidgets( true );
}



// Email the contact
void ContactFrame::sendEmail()
{
  if ( contact_ != 0 )
  {
    currentAccount_->openHotmailAtCompose( contact_->getHandle() );
  }
}



// Show the contact's profile
void ContactFrame::showProfile()
{
  QString    urlPath;
  KURL      *url;
  KRun      *run;

  if ( contact_ != 0 )
  {
    // Set a path to the msn profile page.  Unfortunately, this isn't
    //  internationalized.
    urlPath = "http://members.msn.com/default.msnw?mem=" + contact_->getHandle();
    // Create a URL to the given path
    url = new KURL( urlPath );
    // Launch the default html program for the given URL
  	run = new KRun( *url );
  }
}



// Receive notice that the contact is typing
void ContactFrame::startTyping()
{
  QImage  glowingImage;
  QPixmap contactPicture;

  glowingImage = contactImage_.copy();
  KIconEffect::toGamma( glowingImage, 0.8 );
  contactPicture.convertFromImage( glowingImage );
  contactPixmapLabel_->setPixmap( contactPicture );

  // Make the contact picture glow
  // Start the timer to disable the label
  typingTimer_.start(5000, true);
}



// Disable the typing label when the timer has timed out
void ContactFrame::stopTyping()
{
  QPixmap contactPicture;

  contactPicture.convertFromImage( contactImage_ );
  contactPixmapLabel_->setPixmap( contactPicture );
}



// Update the contact picture
void ContactFrame::updatePicture()
{
  QPixmap      contactPicture;

  if ( contact_ != 0 )
  {
#ifdef KMESSDEBUG_CONTACTFRAME
    kdDebug() << "ContactFrame - UpdatePicture - Contact picture path is " << contact_->getContactPicturePath() << endl;
#endif
    bool loaded = contactImage_.load( contact_->getContactPicturePath() );

    // Load default if custom image could not be loaded
    if(! loaded)
    {
      loaded = contactImage_.load( contact_->getContactDefaultPicturePath() );
    }

    // Display the image
    if(loaded)
    {
      contactPicture.convertFromImage( contactImage_ );
      contactPixmapLabel_->setPixmap( contactPicture );
    }
  }
}



// Update the status widgets
void ContactFrame::updateStatusWidgets()
{
  KIconLoader *loader = KGlobal::iconLoader();
  QString      label, statusIdentifier, iconName;
  QString      status;

  if ( contact_ != 0 )
  {
    status = contact_->getStatus();

    if ( status == "AWY" )
    {
      statusIdentifier = i18n( "Away" );
      iconName = "away";
    }
    else if ( status == "BRB" )
    {
      statusIdentifier = i18n( "Be Right Back" );
      iconName = "berightback";
    }
    else if ( status == "BSY" )
    {
      statusIdentifier = i18n( "Busy" );
      iconName = "busy";
    }
    else if ( status == "FLN" )
    {
      statusIdentifier = i18n("Offline");
      iconName = "offline";
    }
    else if ( status == "IDL" )
    {
      statusIdentifier = i18n( "Away - Idle" );
      iconName = "away";
    }
    else if ( status == "LUN" )
    {
      statusIdentifier = i18n( "Out to Lunch" );
      iconName = "lunch";
    }
    else if ( status == "NLN" )
    {
      statusIdentifier = i18n( "Online" );
      iconName = "online";
    }
    else if ( status == "PHN" )
    {
      statusIdentifier = i18n( "On the Phone" );
      iconName = "onthephone";
    }
    label = contact_->getFriendlyName() + "  (" + statusIdentifier + ")";
    statusLabel_->setText( label );
    statusPixmapLabel_->setPixmap( loader->loadIcon( iconName, KIcon::User ) );
  }
}



// Update all the widgets based on the given contact
void ContactFrame::updateWidgets()
{

  if ( contact_ == 0 )
  {
    kdDebug() << "ContactFrame::updateWidgets() - This contact frame hasn't been activated properly." << endl;
    return;
  }
  updatePicture();
  updateStatusWidgets();
  handleLabel_->setText( contact_->getHandle() );

}

#include "contactframe.moc"
