/***************************************************************************
                          newsystemtraywidget.cpp  -  description
                             -------------------
    begin                : Mon Aug 31 2009
    copyright            : (C) 2009 by Valerio Pilo
    email                : valerio@kmess.org
 ***************************************************************************/

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

#include "../contact/msnstatus.h"
#include "../utils/kmessshared.h"
#include "../currentaccount.h"
#include "../account.h"
#include "../kmessdebug.h"
#include "config-kmess.h"

#include <QDesktopWidget>
#include <QDir>
#include <QPainter>
#include <QPixmap>
#include <QTemporaryFile>

#include <KApplication>
#include <KIconEffect>
#include <KLocale>
#include <KMessageBox>
#include <KMenu>
#include <KStandardDirs>



// The constructor
SystemTrayWidget::SystemTrayWidget( QWidget *parent )
 : KStatusNotifierItem( "kmess", parent )
{
  CurrentAccount *currentAccount_ = CurrentAccount::instance();

  // Connect the "changed status" and "changed friendly name" signals
  connect( currentAccount_, SIGNAL(       changedStatus() ),
           this,            SLOT  (       statusChanged() ) );
  connect( currentAccount_, SIGNAL( changedFriendlyName() ),
           this,            SLOT  (       statusChanged() ) );

  // Connect email related signals
  connect( currentAccount_, SIGNAL( changedNoEmails() ),
           this,            SLOT  (       statusChanged() ) );
  connect( currentAccount_, SIGNAL( changedEmailDisplaySettings() ),
           this,            SLOT  (       statusChanged() ) );

  // Set up the static details of the icon
  setCategory( KStatusNotifierItem::Communications );
  setStatus( KStatusNotifierItem::Active );
  setIconByName( "kmess" );
  setTitle( i18n( "KMess" ) );

  // This icon is temporary
  setAttentionIconByName( "preferences-desktop-notification-bell" );

  statusChanged();
}



/**
 * Display an Hide On Close dialog window with a trayicon screenshot
 *
 * This method, taken from the Basket Note Pads project (see the related links below), is used when
 * the user closes the main KMess contact list window. Then a custom dialog window is shown to notify
 * that the app will still run in background. This useful method adds to it a screenshot of the system
 * tray area of the users' desktop, highlighting the application's icons.
 * The original code was KDE3, it's been ported to make better use of the new features of Qt4 and KDE4.
 *
 * @see http://basket.kde.org/ - Official site of the Basket Note Pads project
 * @see http://basket.kde.org/systemtray-on-close-info.php - Specific tray dialog page
 */
void SystemTrayWidget::displayCloseMessage( QString /*fileMenu*/ )
{
  // Don't do all the computations if they are unneeded:
  if ( ! KMessageBox::shouldBeShownContinue("hideOnCloseInfo") )
  {
    return;
  }

  const QString message( i18n( "<p>Closing the main window will keep KMess running in the system tray.</p>"
                               "<p>You can open KMess again by clicking on the bird icon, which is "
                               "now flashing.<br/>"
                               "Use 'Quit' from the 'Connect' menu to quit the application.</p>" ) );

#ifdef KMESSDEBUG_SYSTEMTRAY
  kmDebug() << "Displaying close-to-tray dialog.";
#endif

  // Make the icon to blink to help the user find it
  setStatus( KStatusNotifierItem::NeedsAttention );

  KMessageBox::information( kapp->activeWindow(),
                            message,
                            i18n( "Docking in System Tray" ),
                            "hideOnCloseInfo" );

  // Stop the blinking
  setStatus( KStatusNotifierItem::Active );
}



// The destructor
SystemTrayWidget::~SystemTrayWidget()
{
#ifdef KMESSDEBUG_SYSTEMTRAY
  kmDebug() << "DESTROYED.";
#endif
}



// Enable the system tray icon
void SystemTrayWidget::enable()
{
  // Force changing the icon
  statusChanged();
}



// Return the context menu
KMenu* SystemTrayWidget::menu() const
{
  return contextMenu();
}



// Change the icon when the user's status changes
void SystemTrayWidget::statusChanged()
{
  QString          friendlyName;
  QString          displayPicture;
  Status status = STATUS_OFFLINE;

  CurrentAccount *account = CurrentAccount::instance();
  status = account->getStatus();

  if ( status != STATUS_OFFLINE )
  {
#ifdef KMESSDEBUG_SYSTEMTRAY
    kmDebug() << "Updating icon status to" << MsnStatus::getCode( status );
#endif

    if( ! account->isVerified() )
    {
      // The account is not verified, use the email address
      friendlyName = account->getHandle();
    }
    else
    {
#if defined( Q_WS_WIN )
        friendlyName = account->getFriendlyName( STRING_CLEANED );
#else
        friendlyName = account->getFriendlyName( STRING_CLEANED_ESCAPED );
#endif
    }

    if( status != STATUS_OFFLINE )
    {
      displayPicture = account->getPicturePath();
    }
  }
  else
  {
#ifdef KMESSDEBUG_SYSTEMTRAY
    kmDebug() << "Updating icon";
#endif
  }

  if( displayPicture.isNull() )
  {
    displayPicture = KIconLoader::global()->iconPath( "kmess", KIconLoader::Desktop );
  }

  // Set the tray and the tooltip icons
  setToolTipIconByName( displayPicture );
  setOverlayIconByName( ( status != STATUS_OFFLINE )
                          ? MsnStatus::getIconName( status )
                          : QString() );

  // Update the tooltip
  QString newTooltip;

  if( status != STATUS_OFFLINE )
  {
#if defined( Q_WS_WIN )
    // Qt on Windows does not support html in the system tray widget
    newTooltip = i18nc( "Tray icon text tooltip when connected, %1 is the friendly name, %2 is the status",
                        "Connected as %1 (%2)", friendlyName, MsnStatus::getName( status ) );
#else
    // Tray icon tooltip, in html
    newTooltip = i18nc( "Tray icon HTML tooltip when connected, %1 is the friendly name, %2 is the status",
                        "<p>Connected as:<br/><b>%1</b> (%2)</p>", friendlyName, MsnStatus::getName( status ) );
#endif
  }
  else
  {
#if defined( Q_WS_WIN )
    newTooltip = i18nc( "Tray icon text tooltip when not connected",
                        "Not connected" );
#else
    newTooltip = i18nc( "Tray icon HTML tooltip when not connected",
                        "<p>Not connected</p>" );
#endif
  }

  // Little html "hack" to not show the version in bold. Not guaranteed to keep working buuuut..
  setToolTipTitle( i18n( "KMess" ) + "</b><br/><small>" + KMESS_VERSION + "</small><b>" );

  setToolTipSubTitle( newTooltip );
}



#include "newsystemtraywidget.moc"
