/********************************
*******************************************
 *   Copyright (C) 2005 by Giorgio Alfarano   *
 *   openc6@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.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/

#include <kapplication.h>
#include <ksystemtray.h>
#include <kpopupmenu.h>
#include <kaction.h>
#include <qtimer.h>
#include <qcursor.h>
#include <qdatetime.h>
#include <c6trayicon.h>
#include "../../../src/c6pixmapcache.h"
#include "../../../src/c6global.h"
#include "../../../src/chatview.h"
#include "../../../src/c6.h"
#include <qtimer.h>
#include "kdegui.h"

extern "C" void* defaultFactoryFunction(void)
{
    return new KdeGuiFactory;
}

static QString getCurrentTimeStr()
{
    QString loc = QTime::currentTime(Qt::LocalTime).toString();
    return(loc);
}

KdeGuiPlugin::KdeGuiPlugin()
        :_trayIcon(0)
        ,_trayList(0)
        ,_trayIconTimer(0)
{
    // this is mandatory if this is a kde plugin
    setForKde();
    _incomingMessageList.setAutoDelete(TRUE);
}

KdeGuiPlugin::~ KdeGuiPlugin()
{
    if (canDestroy() == true)
    {
        delete static_cast<KApplication*>(getKdeEntryPoint());
    }
}

QApplication* KdeGuiPlugin::createKApplication()
{
    KApplication *kapplication=0;

    if (isForKde() == true)
    {
        int a =0;
        char *argv[1];
        *argv = new char[1];

        kapplication = new KApplication(a,argv,"kapp");
        setKdeEntryPoint(kapp);
    }
    return(static_cast<QApplication*>(kapplication));
}

QString KdeGuiPlugin::getName()
{
    return("KDEGUI");
}

QString KdeGuiPlugin::getDescription()
{
    return("Supporto per icona nella system tray");
}

void KdeGuiPlugin::initialize()
{
    C6PixmapCache &pixmap = C6PixmapCache::getInstance();
    C6Global &global = C6Global::getInstance();
    QString path = global.getSkinPath();
    
    _trayOrdinary[AVAILABLE]  = const_cast<QPixmap*>(&pixmap.getPixmap(path+"Contact_green_mini.png"));
    _trayOrdinary[AWAY] =   const_cast<QPixmap*>(&pixmap.getPixmap(path+"Contact_away_mini.png"));
    _trayOrdinary[BUSY] = const_cast<QPixmap*>(&pixmap.getPixmap(path+"Contact_busters_mini.png"));
    _trayOrdinary[NETFRIEND]  = const_cast<QPixmap*>(&pixmap.getPixmap(path+"Contact_block_mini.png"));

    _trayIcon = new C6TrayIcon(C6::self()->getMainDialogPtr(),"kdegui");
    _trayList = new KPopupMenu(_trayIcon);
    _trayIconTimer = new QTimer(this);

    connect(_trayList,SIGNAL(activated(int)),this,SLOT(trayListClicked(int)));
    connect(_trayIcon,SIGNAL(quitSelected()),this,SLOT(trayQuitSelected()));
    connect(_trayIconTimer,SIGNAL(timeout()),this,SLOT(trayTimerDone()));
    connect(C6::self(),SIGNAL(online()),this,SLOT(showSysTray()));
    connect(C6::self(),SIGNAL(restoreLoginSession()),this,SLOT(hideSysTray()));
    connect(C6::self(),SIGNAL(enqueueIncomingMessage(QString,QString&,void*)),
            this,SLOT(enqueueIncomingMessage(QString,QString&,void*)));
    connect(C6::self(),SIGNAL(chatHasFocus(ChatView*)),
            this,SLOT(removeMessageFromList(ChatView*)));
    connect(C6::self(),SIGNAL(statusChanged(C6Users::C6USER_STATUS)), this,SLOT(setIconStatus(C6Users::C6USER_STATUS)));
    connect(_trayIcon,SIGNAL(incomingClicked()),this,SLOT(trayIconClicked()));
    connect(_trayIcon,SIGNAL(incomingDoubleClicked()),this,SLOT(trayIconDoubleClicked()));
}

/*!
    \fn KdeGuiPlugin::trayIconClicked()
 */
void KdeGuiPlugin::trayIconClicked()
{
    C6PixmapCache &pixcache = C6PixmapCache::getInstance();
    C6Global &global = C6Global::getInstance();
    QString path = global.getSkinPath();

    QPixmap &chatIcon =
        const_cast<QPixmap&>(pixcache.getPixmap(path+"filetypes.png"));
    QPixmap &chatEntryIcon =
        const_cast<QPixmap&>(pixcache.getPixmap(path+"blupenguin16x16.png"));

    _trayList->clear();
    _trayList->insertTitle(chatIcon,NEWMESSAGESTR);

    int i=1;

    for (C6Msg *temp = _incomingMessageList.first(); temp;
            temp = _incomingMessageList.next())
    {
        _trayList->insertItem(QIconSet(chatEntryIcon),temp->getTime()+
                              " "+temp->getNick()+" ("+
                              QString::number(temp->getCounter())+")",i);
        i++;
    }

    _trayList->popup(QCursor::pos());
}


/*!
    \fn KdeGuiPlugin::trayIconDoubleClicked()
 */
void KdeGuiPlugin::trayIconDoubleClicked()
{
    _trayIcon->setActive();
    trayListClicked(_incomingMessageList.count());
}


/*!
    \fn KdeGuiPlugin::trayListClicked(int id)
 */
void KdeGuiPlugin::trayListClicked(int id)
{
    Q_ASSERT(id);

    C6Msg *temp= _incomingMessageList.at(id-1);

    if (temp != 0)
    {
        QWidget *chat = reinterpret_cast<QWidget*>(temp->getPtr());

        if (chat != 0)
        {
            if (C6Global::getInstance().getTabActivated())
            {
                ChatView *chatWidget = reinterpret_cast<ChatView*>(chat);
                QWidget *tabChatPtr = C6::self()->getTabDialogPtr();

                Q_CHECK_PTR(tabChatPtr);

                if (tabChatPtr != 0)
                {
                    C6::self()->restoreWidget(*tabChatPtr);
                }

                C6::self()->setTabTo(chatWidget->getOtherNick());
            }
            else
            {
                C6::self()->restoreWidget(*chat);
            }
        }
    }
}


/*!
    \fn KdeGuiPlugin::trayTimerDone()
 */
void KdeGuiPlugin::trayTimerDone()
{
    _trayIcon->trayTimerDone();
}

void KdeGuiPlugin::trayIconFlashStart()
{
    if (!_trayIcon->isFlashing())
    {
        _trayIcon->flashTrayIconStart();
        _trayIconTimer->start(550);
    }
}

void KdeGuiPlugin::trayIconFlashStop()
{
    _trayIconTimer->stop();
    _trayIcon->flashTrayIconStop();
}

void KdeGuiPlugin::trayQuitSelected()
{
    C6::self()->forceClientExit();
}


/*!
    \fn KdeGuiPlugin::showSysTray()
 */
void KdeGuiPlugin::showSysTray()
{
    _trayIcon->show();
}

void KdeGuiPlugin::hideSysTray()
{
    _trayIcon->hide();
    trayIconFlashStop();
}


/*!
    \fn KdeGuiPlugin:: enqueueIncomingMessage(const QString & time,const QString &nick,void* pchat); 
 */
void KdeGuiPlugin::enqueueIncomingMessage(QString time,QString &nick,void* pchat)
{
    C6Msg *t=0;
    bool found = false;
    QString nickFrom = nick;

    for (t = _incomingMessageList.first(); t; t = _incomingMessageList.next())
    {
        if (t->getNick().compare(nickFrom) == 0)
        {
            found = true;
            break;
        }
    }

    if (found == true)                                      // already a message in queue
    {
        t->update(getCurrentTimeStr());
    }
    else
    {
        _incomingMessageList.append(new C6Msg(time,nickFrom,pchat,1));
        trayIconFlashStart();
    }
}


/*!
    \fn KdeGuiPlugin::removeMessageFromList(void*)
 */
void KdeGuiPlugin::removeMessageFromList(ChatView *p)
{
    if (p != 0)
    {
        for (C6Msg *temp = _incomingMessageList.first(); temp; temp = _incomingMessageList.next())
        {
            if (temp->getNick().compare(p->getOtherNick()) == 0)
            {
                _incomingMessageList.remove(temp);
            }
        }

        if (_incomingMessageList.count() == 0)
        {
            trayIconFlashStop();
        }
    }
}

void  KdeGuiPlugin::setIconStatus(C6Users::C6USER_STATUS status)
{
    int index = -1;

    switch (status)
    {
    case  C6Users::U_BUSY:
        index = BUSY;
        break;
    case  C6Users::U_AWAY:
        index = AWAY;
        break;
    case  C6Users::U_NETFRIENDONLY:
        index = NETFRIEND;
        break;
    case  C6Users::U_AVAILABLE:
        index = AVAILABLE;
        break;
    default:
        break;
    }

    if (index != -1)
    {
        _trayIcon->setTrayIcon(_trayOrdinary[index]);
    }
}

#include "kdegui.moc"
