/***************************************************************************
                          c6_main.cpp  -  description
                             -------------------
    begin                : Sat Feb 15 2003
    copyright            : (C) 2003 by Giorgio A.
    email                : 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.                                   *
 *                                                                         *
 ***************************************************************************/
#include "config.h"
#include "c6_main.h"
#include <qwidget.h>
#include <qpopupmenu.h>
#include <qlistview.h>
#include <qcombobox.h>
#include <qcursor.h>
#include <qlabel.h>
#include <qgroupbox.h>
#include <qevent.h>
#include <qfont.h>
#include <qlayout.h>
#include <qheader.h>
#include <qpainter.h>
#include <qapplication.h>
#include <qtooltip.h>
#include "c6button.h"
#include "c6pixmapcache.h"
#include "c6settings.h"
#include "c6global.h"
#include "c6proto.h"
#include <qtooltip.h>
#include <qtextedit.h>
#include <qstringlist.h>
#include <qlineedit.h>
#include <qstatusbar.h>
#include <qmenubar.h>
#include <qaction.h>
#include <qfontmetrics.h>
#include <qmessagebox.h>
#include "c6usersmanager.h"
#include "c6photoretriever.h"
#include "c6contactlistitem.h"

static const QString USERONLINESTR = "Utenti Online: ";
static const QString DEFAULT_MESSAGE_ODD = "Digita qui il tuo messaggio....";
static const QString NICK_ALERT_OP_MSG = "Selezionare un gruppo dalla lista contatti !";
static const QString SELECT_NICK_ALERT_OP_MSG = "Selezionare un contatto !";
static C6Users::C6USER_STATUS combo2Status[4]={C6Users::U_AVAILABLE,
        C6Users::U_NETFRIENDONLY,C6Users::U_BUSY,
        C6Users::U_AWAY};

static int Status2Combo(C6Users::C6USER_STATUS status)
{
    int ret =   C6Users::U_AVAILABLE;

    switch(status)
    {
    case C6Users::U_AVAILABLE:
        ret = 0;
        break;
    case C6Users::U_NETFRIENDONLY:
        ret = 1;
        break;
    case C6Users::U_BUSY:
        ret = 2;
        break;
    case C6Users::U_AWAY:
        ret = 3;
        break;
    default:
        break;
    }

    return(ret);
}

static bool isKdePluginLoaded()
{
    C6Global &global = C6Global::getInstance();
    QStringList tmp = global.getLoadedPluginName();
    bool found = false;

    for (unsigned int i=0; i < tmp.count(); i++)
    {
        if (tmp[i].compare("KDEGUI") == 0)
        {
            found = true;
            break;
        }
    }

    return(found);
}

C6_Main::C6_Main(QWidget *parent, const char *name ) : MainDlg(parent,"C6_Main")
        ,_listType(NETFRIEND_LIST)
        ,_groupMenu(0)
        ,_userMenu(0)
        ,_subUserMenu(0)
        ,_mainMenu(0)
        ,_subList(0)
        ,_subListFromMenu(0)            
        ,_messageODD("none")
        ,_photoRetriever(0)
        ,_menuBar(new QMenuBar(menuFrame))
{
    C6Global &global = C6Global::getInstance();
    C6PixmapCache &pix = C6PixmapCache::getInstance();
    QString path = global.getSkinPath();

    buildMenus();       
    
    FriendListView->header()->hide();
    FriendListView->clear();
    FriendListView->setSorting(-1);
    FriendListView->setColumnAlignment(1,Qt::AlignRight);
    FriendListView->setColumnWidthMode(1,QListView::Manual);
    FriendListView->setColumnWidth(1,35);        
    
    statusPixmap[0] = const_cast<QPixmap*>(&pix.getPixmap(path+"Contact_green.png"));
    statusPixmap[1] = const_cast<QPixmap*>(&pix.getPixmap(path+"Contact_block.png"));
    statusPixmap[2] = const_cast<QPixmap*>(&pix.getPixmap(path+"Contact_busters.png"));
    statusPixmap[3] = const_cast<QPixmap*>(&pix.getPixmap(path+"Contact_away.png"));

    _freeIcon =  statusPixmap[0];
    _busyIcon =  statusPixmap[2];
    _awayIcon = statusPixmap[3];
    _netfriendIcon = statusPixmap[1];
    _messagedIcon = const_cast<QPixmap*>(&pix.getPixmap(path+"unreadmessage_list.png"));
    _specialIcon = const_cast<QPixmap*>(&pix.getPixmap(path+"Contact_preferiti.png"));
    _offlineIcon = const_cast<QPixmap*>(&pix.getPixmap(path+"Contact_off.png"));
    _groupIcon = const_cast<QPixmap*>(&pix.getPixmap(path+"group_folder.png"));
    setIcon(pix.getPixmap(path+"icon16x16.png"));

    setShowOnline(C6Settings::getInstance().getShowOnline());

    exitButtonPlaceHolder->hide();
    C6Button *exitButton = new C6Button(frame15,0,0,path+"lista_contatti_17.png",path+"lista_contatti_over_17.png");
    layout33->addWidget(exitButton);
    connect(exitButton,SIGNAL(clicked()),this,SLOT(closeMain()));
    QToolTip::add
        (exitButton,QString::fromUtf8("Termina la connessione"));

    menuButtonPlaceHolder->hide();
    C6Button *menuButton = new C6Button(frame6,0,0,path+"menu_09.png",path+"menu_over_09.png",
                                        QString::null,Qt::ThresholdDither);
    connect(menuButton,SIGNAL(clicked()),this,SLOT(menuClicked()));
    QToolTip::add
        (menuButton,QString::fromUtf8("Menù principale"));

    QWidget *upParent = reinterpret_cast<QWidget*>(aboutButtonPlaceHolder->parent());
    C6Button* aboutButton = new C6Button(upParent,0,0,path+"lista_contatti_15.png",
                                         path+"lista_contatti_over_15.png",
                                         path+"lista_contatti_over_15.png");
    QToolTip::add
        (aboutButton,"Informazioni su OpenC6");
    aboutButtonPlaceHolder->hide();
    layout34->addWidget(aboutButton);
    connect(aboutButton,SIGNAL(clicked()),this,SLOT(aboutClicked()));
    
    connect(FriendListView,SIGNAL(doubleClicked(QListViewItem *)),this,SLOT(openChat(QListViewItem *)));
    connect(FriendListView,SIGNAL(contextMenuRequested(QListViewItem *,const QPoint &,int)),this,SLOT(showMenus(QListViewItem *,const QPoint &,int)));

    connect(StatusSwitch,SIGNAL(activated(int)),this,SLOT(changeStatus(int)));
    setOnlineStatus(C6Settings::getInstance().getStatus());

    _tip = new C6ContactListTip(FriendListView);
    global.setBehaviourIfMacOSX(FriendListView);

    connect(messageODD,SIGNAL(returnPressed()),this,SLOT(messageODDReturnPressed()));
    connect(messageODD,SIGNAL(lostFocus()),this,SLOT(messageODDLostFocus()));

    _photoRetriever = new C6PhotoRetriever();

    connect(_photoRetriever,SIGNAL(photoReady(QByteArray&,const QString&)),
            SLOT(setPhoto(QByteArray&,const QString&)));
    
   setListType(NETFRIEND_LIST);   
}

C6_Main::~C6_Main()
{
    delete _groupMenu;
    delete _userMenu;
    delete _mainMenu;
    delete _tip;
}

void C6_Main::closeMain()
{
    emit SendClose();
}

void C6_Main::closeEvent(QCloseEvent *e)
{
#if !defined(Q_OS_MACX) && !defined(Q_OS_DARWIN)
    e->accept();
    if (isKdePluginLoaded() == false)
    {
        emit ForceClose();
    }
#else
    showMinimized();
#endif
}

void C6_Main::menuClicked()
{
    _mainMenu->exec(QCursor::pos());
}

void C6_Main::changeStatus(int status)
{
    setOnlineStatus(status);
    emit changeMyStatus(combo2Status[status]);
}

bool C6_Main::event(QEvent * e)
{
    if (e->type() == QEvent::ShowMinimized)
    {
        if (isKdePluginLoaded() == true)
        {
            hide();
            return true;
        }
    }
    else
    {
        return MainDlg::event(e);
    }
}


/*!
    \fn C6_Main::setOwnerName(QString &)
 */
void C6_Main::setOwnerName(QString const & name)
{
    identityName = name;
    setCaption(C6NAME+" ("+identityName+")");
}


/*!
    \fn C6_Main::getIdentityName()
 */
const QString& C6_Main::getIdentityName()
{
    return(identityName);
}

void C6_Main::setShowOnline(bool status)
{
    showOnline = status;
}

bool C6_Main::getShowOnline()
{
    return(showOnline);
}


/*!
    \fn C6_Main::openChat(QListViewItem * item)
 */
void C6_Main::openChat(QListViewItem * item)
{
    if (item != 0)
    {
        if (item->parent() != 0)                                   // is it root ?
        {
            QString name = (static_cast< C6ContactListItem*>(item))->getNick();
            emit buildChat(name);
        }
    }
}


/*!
    \fn C6_Main::showMenus(QListViewItem *,const QPoint &,int)
 */
void C6_Main::showMenus(QListViewItem * menu,const QPoint & point,int a)
{
    if (menu != 0)
    {
        if (menu->parent() == 0)                                   // root menu
        {
            int choose = _groupMenu->exec(point);
            if (choose != -1)
            {                     
                emit userMenuAction(menu->text(0),static_cast<USER_MENU_ACTIONS>(choose));            
                
                if ((choose == SHOW_FRIENDS) || (choose == SHOW_WHITE))
                {               
                    refreshList(true);              
                }               
            }            
        }
        else
        {
            C6Global &global = C6Global::getInstance();
            C6PixmapCache &pix = C6PixmapCache::getInstance();
            QString path = global.getSkinPath();

            QStringList groupList = C6Global::getInstance().getAllGroups();
            _subUserMenu->clear();
            for (unsigned int i=0; i < groupList.count(); i++)
            {
                _subUserMenu->insertItem(pix.getPixmap(path+"group_folder.png"),groupList[i],i+MOVE);
            }

            int choose = _userMenu->exec(point);
            if (choose !=-1)
            {
                C6ContactListItem* tmp = static_cast<C6ContactListItem*>(menu);
                emit userMenuAction(tmp->getNick(),static_cast<USER_MENU_ACTIONS>(choose),menu->parent()->text(0));
            }
        }
    }
}


/*!
    \fn C6_Main::setOnlineStatus(int status)
 */
void C6_Main::setOnlineStatus(C6Users::C6USER_STATUS status)
{
    int state = Status2Combo(status);
    setOnlineStatus(state);
}

/*!
    \fn C6_Main::setOnlineStatus(int status)
 */
void C6_Main::setOnlineStatus(int status)
{
    _onlineStatus = status;
    StatusSwitch->setCurrentItem(status);
    statusPix->setPixmap(*statusPixmap[status]);
}

/*!
    \fn C6_Main::getMenuPtr()
 */
QPopupMenu* C6_Main::getMenuPtr()
{
    return(_mainMenu);
}


/*!
    \fn C6_Main::chooseFromMenu(int)
 */
void C6_Main::chooseFromMenu(int choice)
{
    emit signalMenuChoice(choice);
}

/*!
    \fn C6_Main::chooseFromPopupMenu(int)
 */
void C6_Main::chooseFromPopupMenu(int choice)
{
    QListViewItem *selected = FriendListView->selectedItem();    
    bool isSelectedItem = selected != 0;    
    
    switch(choice)
    {                
        case ADDNICK:
            if (isSelectedItem == true)
            {
                bool isRootItem = (selected->parent() == 0);   
                if (isRootItem == true)
                {                               
                    emit userMenuAction(selected->text(0),static_cast<USER_MENU_ACTIONS>(choice));      
                }
                else
                {
                    messageBox(NICK_ALERT_OP_MSG);                    
                }                               
            }       
            else
            {
                messageBox(NICK_ALERT_OP_MSG);     
            }               
            break;         
        case REMOVENICK:
            if (isSelectedItem == true)
            {
                bool isRootItem = (selected->parent() == 0);             
                if (isRootItem == false)
                {                   
                    emit userMenuAction(selected->text(0),static_cast<USER_MENU_ACTIONS>(choice));      
                }
                else
                {
                    messageBox(SELECT_NICK_ALERT_OP_MSG);    
                }                               
            }       
            else
            {
                messageBox(SELECT_NICK_ALERT_OP_MSG);     
            }                    
            break;
        case RENAMEGROUP:
            if (isSelectedItem == true)
            {
                bool isRootItem = (selected->parent() == 0);            
                if (isRootItem == true)
                {
                    emit userMenuAction(selected->text(0),static_cast<USER_MENU_ACTIONS>(choice));      
                }      
                else
                {
                    messageBox(NICK_ALERT_OP_MSG);                    
                }                       
            }   
            else
            {
                messageBox(NICK_ALERT_OP_MSG);               
            }                            
            break;
        case REMOVEGROUP:
            if (isSelectedItem == true)
            {
                bool isRootItem = (selected->parent() == 0);            
                if (isRootItem == true)
                {
                    emit userMenuAction("",static_cast<USER_MENU_ACTIONS>(choice));                
                } 
                else
                {
                    messageBox(NICK_ALERT_OP_MSG);                     
                }                                           
            }  
            else
            {
                messageBox(NICK_ALERT_OP_MSG);                  
            }                        
            break;         
  
            default:
                 emit userMenuAction("",static_cast<USER_MENU_ACTIONS>(choice));     
            break;            
    }           
}

/*!
    \fn C6_Main::addUser2Menu(QStringList &user)
 */
void C6_Main::addUser2Menu(QStringList &user)
{
    nickMenu->clear();
    _mainMenu->removeItem(CHANGENICK);

    if (user.count() > 1)
    {
        C6Global &global = C6Global::getInstance();
        QString path = global.getSkinPath();
        C6PixmapCache &pix = C6PixmapCache::getInstance();

        for(unsigned int i=0; i < user.count(); i++)
        {
            if (user[i] != identityName)
            {
                nickMenu->insertItem(user[i],i);
            }
        }

        _mainMenu->insertItem(QIconSet(pix.getPixmap(path+"reload.png")),
                         "Cambia nick",nickMenu,CHANGENICK,3);
    }
}


/*!
    \fn C6_Main::nickSelected(int nick)
 */
void C6_Main::nickSelected(int nick)
{
    emit newNickReconnect(nick);
}


/*!
    \fn C6_Main::setUsersCount(unsigned int online,unsigned int offline)
 */
void C6_Main::setUsersCount(unsigned int online,unsigned int offline)
{
    Online->setText(USERONLINESTR+QString::number(online)+" su "+QString::number(offline));
}

/*!
    \fn C6_Main::setCustomFont()
 */
void C6_Main::setCustomFont()
{
    C6Settings &settings = C6Settings::getInstance();
    C6Global &global = C6Global::getInstance();
    QFont lfont(global.getBaseFont());
    QFontMetrics fm(lfont);
    
    setFont(lfont);   
    int size = lfont.pointSize()-1;
    if (size > 2)
    {
        lfont.setPointSize(size);
        statistics->setFont(lfont);
        messageODD->setFont(lfont);
        Online->setFont(lfont);              
    }
    
    if (settings.getContactFontSwitch() == true)
    {             
        QFont tmp(settings.getContactFontFamily(),settings.getContactFontSize(),
                settings.getContactFontWeight());    
        FriendListView->setFont(tmp);
    }
    else
    {
        FriendListView->setFont(lfont);
    }         
       
    QColor color(settings.getContactUserForeColor());
    FriendListView->setPaletteForegroundColor(color);
    
    const float menuBarRatio = 1.8;
    menuFrame->setFixedHeight(fm.height()*menuBarRatio);        
}

C6ContactListItem* C6_Main::addListItem(QListViewItem *root,C6Users *tmp,QPixmap *icon)
{
    C6ContactListItem *item = new C6ContactListItem(root,tmp->getNick(),tmp->getDailyMessage());
    if (item != 0)
    {      
        if (C6Global::getInstance().isInSpecialList(tmp->getNick()))
        {
            item->setPixmap(0,*_specialIcon);
        }
        else
        {
            item->setPixmap(0,*icon);
        }
    }
    return(item);
}

/** Refresh the list to update the user status  */
void C6_Main::refreshList(bool clear)
{
    C6Settings &settings = C6Settings::getInstance();
    C6Global &global = C6Global::getInstance();
    C6ContactListItem *item=0;
    QListViewItem *root=0;
    QListViewItem *previousGroup=0;
    int onlineCounter = 0;
    QStringList groups;
    QStringList onlineUsers;
    
    if (clear == true)
    {
        FriendListView->clear();
    }

    if (_listType == WHITE_LIST)
    {
        groups.append(global.getWhiteListGroupName());
    }
    else
    {
        groups = global.getAllGroups();
    }

    for (unsigned int i=0; i < groups.size(); i++)
    {
        if (previousGroup != 0)            // sort previous group
        {
            previousGroup->sortChildItems(0,!settings.getSortAscending());
        }

        QString group = groups[i];

        root = findGroupItem(group);

        if (root != 0)              // remove all children
        {
            C6ContactListItem* item=0;
            while ((item = static_cast<C6ContactListItem*>(root->firstChild()))
                    != 0)
            {
                delete(item);
            }

            previousGroup = root;
        }
        else                          // create a new Group
        {
            root =  new C6ContactListItem(FriendListView,previousGroup,true);
            root->setText(0,group);
            root->setPixmap(0,*_groupIcon);
            previousGroup = root;
        }

        if (_listType != WHITE_LIST)
        {
            C6Users::C6UsersList &netfriend = global.getC6UsersFromGroup(group);

            for (C6Users *tmp = netfriend.first(); tmp; tmp = netfriend.next())
            {
                switch (tmp->getStatus())
                {
                case C6Users::U_NETFRIENDONLY:
                    item = addListItem(root,tmp,_netfriendIcon);
                    onlineUsers.append(tmp->getNick());               
                    break;
                case C6Users::U_BUSY:
                    item = addListItem(root,tmp,_busyIcon);
                    onlineUsers.append(tmp->getNick());                      
                    break;
                case C6Users::U_AWAY:
                    item = addListItem(root,tmp,_awayIcon);
                    onlineUsers.append(tmp->getNick());                      
                    break;
                case C6Users::U_AVAILABLE:
                    item = addListItem(root,tmp,_freeIcon);
                    onlineUsers.append(tmp->getNick());                      
                    break;
                case C6Users::U_OFFLINE:
                    {
                        if (getShowOnline() == false)
                        {
                            item = new C6ContactListItem(root,tmp->getNick(),"");
                            item->setPixmap(0,*_offlineIcon);
                        }
                    }
                    break;

                default:
                    break;
                }

                if (tmp->getStatus() != C6Users::U_OFFLINE)
                {
                    onlineCounter++;
                }

                if ((tmp->isMessaged() == true) && (tmp->getStatus() != C6Users::U_OFFLINE))
                {
                    if(item != 0)
                    {
                        item->setPixmap(0,*_messagedIcon);
                    }
                }
            }
            cleanOrphanedGroup();
        }
        else
        {
            QStringList whitelist = global.getWhiteListUsers();
            for (unsigned int i=0; i < whitelist.count(); i++)
            {
                C6ContactListItem *item = new C6ContactListItem(root,whitelist[i],"");

                if (item != 0)
                {
                    item->setPixmap(0,*_offlineIcon);
                    
                }
            }
        }
    }

    updateStats(onlineCounter);
    QApplication::postEvent(_photoRetriever,new PhotoListEvent(onlineUsers));
}

void C6_Main::updateStats(int counter)
{
    setUsersCount(counter,C6Global::getInstance().getAllUsers().count());
}

C6Users::C6USER_STATUS C6_Main::getOnlineStatus() const
{
    return(combo2Status[_onlineStatus]);
}

void C6_Main::updateServerStats(const QString &stats)
{
    QStringList tmp = QStringList::split("\n",stats);

    if (tmp.count() == 3)
    {
        statistics->setText("\n"+tmp[2]);
    }
    else
    {
        statistics->setText("");
    }
}

void C6_Main::cleanOrphanedGroup()
{
    QListViewItem *groupItem = FriendListView->firstChild();

    while(groupItem != 0)
    {
        if (C6Global::getInstance().groupIsPresent(groupItem->text(0)) == false)
        {
            delete groupItem;
        }
        groupItem =groupItem->nextSibling();
    }
}

QListViewItem* C6_Main::findGroupItem(const QString & group)
{
    QListViewItem* groupItem = FriendListView->firstChild();
    QListViewItem* returnItem = 0;

    while(groupItem != 0)
    {
        if (group.compare(groupItem->text(0)) == 0)
        {
            returnItem = groupItem;
            break;
        }
        groupItem = groupItem->nextSibling();
    }

    return(returnItem);
}

void C6_Main::aboutClicked()
{
    emit showAbout();
}



/*!
    \fn C6_Main::setListType(TYPE_LIST type)
 */
void C6_Main::setListType(LIST_TYPE type)
{
    _listType = type;

    switch(type)
    {
    case NETFRIEND_LIST:
        {
            for(unsigned int i=0; i < _groupMenu->count(); i++)
            {
                _groupMenu->setItemVisible(_groupMenu->idAt(i),true);
            }
            _groupMenu->setItemVisible(REVOKE_AUTH,false);

            for(unsigned int i=0; i < _userMenu->count(); i++)
            {
                _userMenu->setItemVisible(_userMenu->idAt(i),true);
            }
            _userMenu->setItemVisible(REVOKE_AUTH,false);
        }
        break;
    case WHITE_LIST:
        {
            _groupMenu->setItemVisible(ADDGROUP,false);
            _groupMenu->setItemVisible(REMOVEGROUP,false);
            _groupMenu->setItemVisible(RENAMEGROUP,false);
            _groupMenu->setItemVisible(TOGGLEONLINE,false);

            for(unsigned int i=0; i < _userMenu->count(); i++)
            {
                _userMenu->setItemVisible(_userMenu->idAt(i),false);
            }

            _userMenu->setItemVisible(REVOKE_AUTH,true);
        }
        break;
    case BLACK_LIST:
        break;
    }
}


/*!
    \fn C6_Main::showListCheckFromMenu()
 */
void C6_Main::showListCheckFromMenu()
{
    fillListCheck(_subListFromMenu);
}

/*!
    \fn C6_Main::showListCheck()
 */
void C6_Main::showListCheck()
{
    fillListCheck(_subList);
}

/*!
    \fn C6_Main::fillListCheck(QPopupMenu *menu)
 */
void C6_Main::fillListCheck(QPopupMenu *menu)
{
    C6PixmapCache &pix = C6PixmapCache::getInstance();
    QString path = C6Global::getInstance().getSkinPath();

    menu->clear();

    if (_listType == NETFRIEND_LIST)
    {
        menu->insertItem(pix.getPixmap(path+"ok.png"),"Amici",SHOW_FRIENDS);
        menu->insertItem(pix.getPixmap(""),"Autorizzati",SHOW_WHITE);
    }
    else
    {
        menu->insertItem(pix.getPixmap(""),"Amici",SHOW_FRIENDS);
        menu->insertItem(pix.getPixmap(path+"ok.png"),"Autorizzati",SHOW_WHITE);
    }

}


/*!
    \fn C6_Main::setListCheck(int)
 */
void C6_Main::setListCheck(int id)
{
    if (id == SHOW_FRIENDS)
    {
        setListType(NETFRIEND_LIST);
    }
    else
    {
        setListType(WHITE_LIST);
    }
}

/*!
    \fn C6_Main::setListCheckAndRefresh(int)
 */
void C6_Main::setListCheckAndRefresh(int id)
{
    setListCheck(id);
    refreshList(true);
}


/*!
    \fn C6_Main::setMessageODD(QString const& message)
 */
void C6_Main::setMessageODD(QString const& message)
{
    if ((message == QString::null) || (message.compare("none") == 0))
    {
        messageODD->setText(DEFAULT_MESSAGE_ODD);
        _messageODD = "none";
    }
    else
    {
        messageODD->setText(message);
        _messageODD = message;
    }
    messageODD->setCursorPosition(0);       
}


/*!
    \fn C6_Main::getMessageODD
 */
QString C6_Main::getMessageODD() const
{
    return _messageODD;
}


/*!
    \fn C6_Main::messageODDReturnPressed()
 */
void C6_Main::messageODDReturnPressed()
{
    _messageODD = messageODD->text();
    emit changeMyStatus(getOnlineStatus(),_messageODD);
}


/*!
    \fn C6_Main::messageODDLostFocus()
 */
void C6_Main::messageODDLostFocus()
{
    setMessageODD(_messageODD);
}

/*!
    \fn C6_Main::setPhoto(QByteArray& data,const QString& filename)
 */
void C6_Main::setPhoto(QByteArray& data,const QString& filename)
{
    QString tmp = filename;
    int commaIndex = filename.find(',');
    
    if (commaIndex != -1)
    {
        QListViewItemIterator it(FriendListView);

        for ( ; it.current(); ++it )
        {
            C6ContactListItem* tmp = static_cast<C6ContactListItem*>(it.current());         
            if (tmp->getNick().compare(filename.left(commaIndex)) == 0)
            {
                QPixmap photo(data);
                if (photo.width() > C6ContactListItem::DEFAULT_PHOTO_WIDTH  || 
                    photo.height() > C6ContactListItem::DEFAULT_PHOTO_WIDTH)
                {
                    photo.resize(C6ContactListItem::DEFAULT_PHOTO_WIDTH,C6ContactListItem::DEFAULT_PHOTO_WIDTH);     
                }               
                
                it.current()->setPixmap(1,photo);
                break;
            }
        }
    }
}

/*!
    \fn C6_Main::buildMenus()
 */
void C6_Main::buildMenus()
{
    C6Global &global = C6Global::getInstance();
    C6PixmapCache &pix = C6PixmapCache::getInstance();
    QString path = global.getSkinPath();
    
    _groupMenu = new QPopupMenu(this);
    _subList = new QPopupMenu(this);
    _userMenu = new QPopupMenu(this);
    _subUserMenu = new QPopupMenu(this);
    _mainMenu = new QPopupMenu(this);
    
    connect(_subList,SIGNAL(aboutToShow()),this,SLOT(showListCheck()));
    connect(_subList,SIGNAL(activated(int)),this,SLOT(setListCheck(int)));

    _groupMenu->insertItem(pix.getPixmap(path+"contents.png"),"Mostra lista",_subList);
    _groupMenu->insertItem(pix.getPixmap(path+"edit_user.png"),"Inizia chat",STARTCHAT);   
    _groupMenu->insertItem(pix.getPixmap(path+"edit_add.png"),"Aggiungi contatto",ADDNICK);
    _groupMenu->insertItem(pix.getPixmap(path+"blupenguin16x16.png"),"Visualizza online/offline",TOGGLEONLINE);
    _groupMenu->insertItem(pix.getPixmap(path+"rotate_cw.png"),"Ordina",SORTORDER);
    _groupMenu->insertItem(pix.getPixmap(path+"group_add.png"),"Aggiungi gruppo",ADDGROUP);
    _groupMenu->insertItem(pix.getPixmap(path+"editcut.png"),"Rimuovi gruppo",REMOVEGROUP);
    _groupMenu->insertItem(pix.getPixmap(path+"rebuild.png"),"Rinomina gruppo",RENAMEGROUP);

    _userMenu->insertItem(pix.getPixmap(path+"decrypted.png"),"Revoca autorizzazione",REVOKE_AUTH);
    _userMenu->insertItem(pix.getPixmap(path+"filetypes.png"),"Apri chat",INITCHAT);
    _userMenu->insertItem(pix.getPixmap(path+"color_line.png"),"Guarda log",USRLOG);
    _userMenu->insertItem(pix.getPixmap(path+"login-photo.png"),"Profilo completo",PROFILE);
    _userMenu->insertItem(pix.getPixmap(path+"login-photo.png"),"Profilo ridotto",ALLPROFILE);
    _userMenu->insertItem(pix.getPixmap(path+"forward.png"),"Sposta contatto a",_subUserMenu);
    _userMenu->insertItem(pix.getPixmap(path+"delete_user.png"),"Elimina contatto",REMOVENICK);

    QPopupMenu* logMenu =  new QPopupMenu(this);
    logMenu->insertItem(pix.getPixmap(path+"color_line.png"),"Log delle conversazioni",USERLOG);
    logMenu->insertItem(pix.getPixmap(path+"color_line.png"),"Log delle stanze",ROOMLOG);
    logMenu->insertItem(pix.getPixmap(path+"color_line.png"),"Log di sistema",SYSLOG);
   
    _mainMenu->insertItem(pix.getPixmap(path+"viewmag.png"),"Ricerca contatto",NETSEARCH);
    _mainMenu->insertItem(pix.getPixmap(path+"toggle_log.png"),"Gestione stanze",ROOMLIST);
    _mainMenu->insertItem(pix.getPixmap(path+"color_line.png"),"Log",logMenu);
    _mainMenu->insertItem(pix.getPixmap(path+"configure.png"),"Preferenze",CONFIG);
    _mainMenu->insertItem(pix.getPixmap(path+"icon16x16.png"),"Informazioni",CREDITS);
    if (global.localNetfriendListExists() == true)
    {         
        _mainMenu->insertItem(pix.getPixmap(path+"exec.png"),"Importa lista",IMPORTLIST);
    }      
    _mainMenu->insertItem(pix.getPixmap(path+"connect_no.png"),"Forza disconnessione",FORCE_EXITMAIN);
    _mainMenu->insertItem(pix.getPixmap(path+"exit.png"),"Disconnetti",EXITMAIN);
    
    connect(_mainMenu,SIGNAL(activated(int)),this,SLOT(chooseFromMenu(int)));
    connect(logMenu,SIGNAL(activated(int)),this,SLOT(chooseFromMenu(int)));

    nickMenu = new QPopupMenu(this);   
    connect(nickMenu,SIGNAL(activated(int)),this,SLOT(nickSelected(int )));    
    
    // application main menu */    
    const float menuBarRatio = 1.8;
    QFontMetrics fm(font());
    menuFrame->setFixedHeight(fm.height()*menuBarRatio);     
    
    QPopupMenu* fileMenu = new QPopupMenu(this);    
    connect(fileMenu,SIGNAL(activated(int)),this,SLOT(chooseFromMenu(int)));   
    
    fileMenu->insertItem(pix.getPixmap(path+"viewmag.png"),"Ricerca contatto",NETSEARCH);   
    fileMenu->insertItem(pix.getPixmap(path+"toggle_log.png"),"Gestione stanze",ROOMLIST);
    fileMenu->insertItem(pix.getPixmap(path+"configure.png"),"Preferenze",CONFIG); 
    if (global.localNetfriendListExists() == true)
    {            
        fileMenu->insertItem(pix.getPixmap(path+"exec.png"),"Importa lista",IMPORTLIST);
    }   
    fileMenu->insertItem(pix.getPixmap(path+"connect_no.png"),"Forza disconnessione",FORCE_EXITMAIN);
    fileMenu->insertItem(pix.getPixmap(path+"exit.png"),"Disconnetti",EXITMAIN);   
    
    _subListFromMenu = new QPopupMenu(this);            
    connect(_subListFromMenu,SIGNAL(aboutToShow()),this,SLOT(showListCheckFromMenu()));
    connect(_subListFromMenu,SIGNAL(activated(int)),this,SLOT(setListCheckAndRefresh(int)));    
    
    QPopupMenu* contactListMenu = new QPopupMenu(this);   
    connect(contactListMenu,SIGNAL(activated(int)),this,SLOT(chooseFromPopupMenu(int)));          
    contactListMenu->insertItem(pix.getPixmap(path+"contents.png"),"Mostra lista",_subListFromMenu);      
    contactListMenu->insertItem(pix.getPixmap(path+"edit_user.png"),"Inizia chat",STARTCHAT);      
    contactListMenu->insertItem(pix.getPixmap(path+"edit_add.png"),"Aggiungi contatto",ADDNICK);
    contactListMenu->insertItem(pix.getPixmap(path+"delete_user.png"),"Elimina contatto",REMOVENICK);   
    contactListMenu->insertItem(pix.getPixmap(path+"group_add.png"),"Aggiungi gruppo",ADDGROUP);
    contactListMenu->insertItem(pix.getPixmap(path+"editcut.png"),"Rimuovi gruppo",REMOVEGROUP);
    contactListMenu->insertItem(pix.getPixmap(path+"rebuild.png"),"Rinomina gruppo",RENAMEGROUP);   
    contactListMenu->insertItem(pix.getPixmap(path+"rotate_cw.png"),"Ordina",SORTORDER);      
    contactListMenu->insertItem(pix.getPixmap(path+"blupenguin16x16.png"),"Visualizza online/offline",TOGGLEONLINE);
   
    QPopupMenu* helpMenu = new QPopupMenu(this);          
    connect(helpMenu,SIGNAL(activated(int)),this,SLOT(chooseFromMenu(int)));      
    helpMenu->insertItem(pix.getPixmap(path+"icon16x16.png"),"Informazioni",CREDITS);   
    
   _menuBar->insertItem("&File",fileMenu);  
   _menuBar->insertItem("&Contatti",contactListMenu);   
   _menuBar->insertItem("&Log",logMenu); 
   _menuBar->insertItem("&Aiuto",helpMenu); 
}

/*!
    \fn C6_Main::messageBox(QString const & cap,QString const & text)
 */
int C6_Main::messageBox(QString const & text)
{
    qApp->beep();
    QMessageBox box("Attenzione",text,QMessageBox::Warning,
                    QMessageBox::Ok,QMessageBox::NoButton,
                    QMessageBox::NoButton,this);
    return(box.exec());
}

void C6_Main::mouseMoveEvent(QMouseEvent * e)
{
    QWidget* tmp = QApplication::widgetAt(mapToGlobal(e->pos()),TRUE);
    if (tmp !=0 && tmp == messageODD)
    {
        QApplication::setOverrideCursor(QCursor(PointingHandCursor));
    }
    else
    {
        QApplication::restoreOverrideCursor();
    }

    MainDlg::mouseMoveEvent(e);
}