/***************************************************************************
                          c6conf.cpp  -  description
                             -------------------
    begin                : Tue Apr 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 <qwidget.h>
#include <qlineedit.h>
#include <qfontdialog.h>
#include <qfiledialog.h>
#include <qstringlist.h>
#include <qtextedit.h>
#include <qcolor.h>
#include <qcolordialog.h>
#include <qtabwidget.h>
#include <qdir.h>
#include <qlabel.h>
#include <qlistbox.h>
#include <qcheckbox.h>
#include <qgroupbox.h>
#include <qmessagebox.h>
#include <qcombobox.h>
#include <qspinbox.h>
#include <qpushbutton.h>
#include <qspinbox.h>
#include <qheader.h>
#include <qlistview.h>
#include <qradiobutton.h>
#include <qbuttongroup.h>
#include <qfontdatabase.h>
#include "c6conf.h"
#include "c6pixmapcache.h"
#include "c6settings.h"
#include "c6global.h"
#include "c6abstractplugin.h"

static QString getFontWeightString(int weight)
{
    QString tmp;

    switch(weight)
    {
    case 50 :
        tmp = "Normal";
        break;
    case 75 :
        tmp = "Bold";
        break;
    default :
        tmp = "";
    }
    return(tmp);
}

C6Conf::C6Conf(QWidget *parent) : configure(parent)
{
    C6Settings &settings = C6Settings::getInstance();
    C6Global  &global = C6Global::getInstance();

    connect(autoRoomEnter,SIGNAL(toggled(bool)),this,SLOT(toggleAutoRoomList(bool)));
    connect(AutoMsg,SIGNAL(toggled(bool)),this,SLOT(toggleMessageEdit(bool)));
    connect(selectFontButton,SIGNAL(clicked()),this,SLOT(selectFontButton_clicked()));
    connect(pluginLoad,SIGNAL(clicked()),this,SLOT(insertPlugin()));
    connect(pluginUnload,SIGNAL(clicked()),this,SLOT(removePlugin()));
    connect(contactFontSwitch,SIGNAL(toggled(bool)),this,SLOT(contactFontToggled(bool)));
    connect(defaultContact,SIGNAL(clicked()),this,SLOT(defaultContactClicked()));
    connect(mapFontSelection,SIGNAL(clicked()),SLOT(mapFontSelectionClicked()));
    connect(defaultListButton,SIGNAL(clicked()),SLOT(defaultListButtonClicked()));
    serverName->setText(settings.getServerName());
    serverPort->setValue(settings.getServerPort().toInt());
    proxyName->setText(settings.getProxyName());
    proxyUser->setText(settings.getProxyUserId());
    proxyPassword->setText(settings.getProxyUserPsw());
    proxyPort->setValue(settings.getProxyPort().toInt());

    startStatusSwitch->setCurrentItem(settings.getStatus());
    NetFriendsEdit->setText(settings.getNetFriendsMessage());
    NetFriendsEdit->setCursorPosition(0);
    BusyEdit->setText(settings.getBusyMessage());
    BusyEdit->setCursorPosition(0);
    BlackListEdit->setText(settings.getBlackListMessage());
    BlackListEdit->setCursorPosition(0);
    AwayEdit->setText(settings.getAwayMessage());
    AwayEdit->setCursorPosition(0);
    AutoMsg->setChecked(settings.getAutoMessage());
    Log->setChecked(settings.getLog());
    LogRoom->setChecked(settings.getRoomLog());
    AutoConnect->setChecked(settings.getAutoConnect());
    Reconnect->setChecked(settings.getReconnect());
    Browser->setText(settings.getBrowser());
    Browser->setCursorPosition(0);
    AutoRaise->setChecked(settings.getAutoRaise());
    AutoPopUp->setChecked(settings.getAutoPopUp());
    SysLog->setChecked(settings.getSysLog());
    ShowOnline->setChecked(settings.getShowOnline());
    soundSwitch->setChecked(settings.getSoundSwitch());
    beepSwitch->setChecked(settings.getBeepSwitch());
    ipShow->setChecked(settings.getIpVisible());
    inMessageSwitch->setChecked(settings.getInMessageSwitch());
    outMessageSwitch->setChecked(settings.getOutMessageSwitch());
    onlineMessageSwitch->setChecked(settings.getOnlineMessageSwitch());
    offlineMessageSwitch->setChecked(settings.getOfflineMessageSwitch());
    soundGroup->setEnabled(settings.getSoundSwitch());
    specialFriendSwitch->setChecked(settings.getSpecialFriendSwitch());
    specialNotifySwitch->setChecked(settings.getSpecialNotifySwitch());

    if (settings.getInMessageWav().length() > 0)
    {
        inMessageWav->setText(settings.getInMessageWav());
    }
    else
    {
        inMessageWav->setText(global.getDefaultSoundPath()+"in.wav");
    }

    if (settings.getOutMessageWav().length() > 0)
    {
        outMessageWav->setText(settings.getOutMessageWav());
    }
    else
    {
        outMessageWav->setText(global.getDefaultSoundPath()+"out.wav");
    }

    if (settings.getOnlineMessageWav().length() > 0)
    {
        onlineMessageWav->setText(settings.getOnlineMessageWav());
    }
    else
    {
        onlineMessageWav->setText(global.getDefaultSoundPath()+"online.wav");
    }

    if (settings.getOfflineMessageWav().length() > 0)
    {
        offlineMessageWav->setText(settings.getOfflineMessageWav());
    }
    else
    {
        offlineMessageWav->setText(global.getDefaultSoundPath()+"offline.wav");
    }

    if (settings.getSpecialFriendWav().length() > 0)
    {
        specialFriendWav->setText(settings.getSpecialFriendWav());
    }
    else
    {
        specialFriendWav->setText(global.getDefaultSoundPath()+"special.wav");
    }

    playCommand->setText(settings.getSoundPlayer());
    dockIcon->setChecked(settings.getDockIcon());
    timeStamp->setChecked(settings.getTimeStampSwitch());
    fileReceivePath->setText(settings.getFileReceivePath());
    startPort->setValue(settings.getStartPort().toInt());
    ForegndColor = settings.getForegndColor();
    FontStyle = settings.getFontStyle();
    FontSize = settings.getFontSize();
    FontWeight = settings.getFontWeight();
    autoAccept->setChecked(settings.getAutoAccept());
    ForeMessageColorUp = settings.getForeMessageColor();
    ForeNetFriendColorUp = settings.getForeNetFriendColor();

    serviceMessagePreview->setPaletteForegroundColor(QColor(ForeMessageColorUp));   
    updateChatPreview(ForegndColor,ForeNetFriendColorUp);
    chatPreview->setFont(QFont(FontStyle,FontSize,FontWeight));

    roomTimeStamp->setChecked(settings.getRoomTimeStamp());
    autoRoomEnter->setChecked(settings.getAutoRoomEnter());
    LogProto->setChecked(settings.getProtoLog());
    selectFontButton->setChecked(settings.getSelectGlobalFont());
    tabbedChat->setChecked(settings.getTabbedChat());
    proxySwitch->setChecked(settings.getProxySwitch());
    proxyAuthSwitch->setChecked(settings.getAuthProxySwitch());
    proxySwitch_toggled(settings.getProxySwitch());
    proxySocksVersion->setCurrentItem(settings.getProxySocksVersion());
    autoAwaySwitch->setChecked(settings.getAutoAway());
    awayMinutes->setValue(settings.getMinutesAway());
    backAutoAwaySwitch->setChecked(settings.getBackAutoAway());

    globalFont.size = settings.getGlobalFontSize();
    globalFont.weight = settings.getGlobalFontWeight();
    globalFont.family = settings.getGlobalFontFamily();
    maxTimeOut->setValue(settings.getLoginTimeout());
    contactFont.size = settings.getContactFontSize();
    contactFont.weight = settings.getContactFontWeight();
    contactFont.family = settings.getContactFontFamily();
    contactFontSwitch->setChecked(settings.getContactFontSwitch());
    contactFontToggled(contactFontSwitch->isChecked());
    soundOnceSwitch->setChecked(settings.getSoundOnce());
    activateStyle->setChecked(settings.getStyleSwitch());            
    
    updateFontText(fontProperty,globalFont.family,globalFont.weight,globalFont.size);
    updateFontText(contactFontProperty,contactFont.family,
                   contactFont.weight, contactFont.size);

    contactGroupColor = settings.getContactGroupForeColor();
    QColor color = QColor(contactGroupColor);

    if (color.isValid())
    {
        groupColor->setPaletteBackgroundColor(color);
    }

    contactUserColor = settings.getContactUserForeColor();
    color = QColor(contactUserColor);

    if (color.isValid())
    {
        userColor->setPaletteBackgroundColor(color);
    }

    selectFontButton_clicked();
    toggleAutoRoomList(settings.getAutoRoomEnter());
    pluginsAvailableList->header()->hide();

    loadPluginListAvailable();
    getLoadedPlugin();
    loadSpecialList();
    loadAutoRoomList();
    loadVisualFontStyle();
    global.setBehaviourIfMacOSX(optionList);   
    
#if defined(Q_OS_MACX) || defined(Q_OS_DARWIN) 
    fileDir->setFlat(true);
    globalFontButton->setFlat(true);
    SelFontUp->setFlat(true);
    netfriendColorButton->setFlat(true);
    myselfColor->setFlat(true);
    ForeMessageUp->setFlat(true);
    contactSelFont->setFlat(true);
    groupNameForeColor->setFlat(true);
    contactForeColor->setFlat(true);
    fileOpen1->setFlat(true);
    playDemo1->setFlat(true);
    fileOpen2->setFlat(true);
    playDemo2->setFlat(true);   
    fileOpen3->setFlat(true);
    playDemo3->setFlat(true);   
    fileOpen4->setFlat(true);
    playDemo4->setFlat(true);   
    fileOpen5->setFlat(true);
    playDemo5->setFlat(true);   
#endif   
    styleCombo->insertStringList(global.getStyleList());
    setStyleCombo(settings.getWidgetStyle());   
     
    const QString fontListComment = "Questa mappa contiene una associazione tra la lista dei font utilizzati nella finestra di chat"
            " dall'utente remoto (a sinistra) e la lista dei font visualizzati e selezionati nella nostra finestra di chat (a destra)"
            ".\nTale mappa si rende necessaria qualora i font utilizzati "
            "dall'utente remoto non siano disponibili localmente nel sistema e quindi non visualizzabili correttamente." ;
    
    fontComment->setText(fontListComment);        
    const QString serviceMessageText = QString::fromUtf8("- Il netfriend pinco.p è appena entrato in chat -");
    serviceMessagePreview->setText(serviceMessageText);   
}


C6Conf::~C6Conf()
{}

void C6Conf::closeEvent(QCloseEvent *e)
{
    e->accept();
}

void C6Conf::Apply_clicked()
{
    postVariableSet();
    saveCurrentSettings(); 
    emit apply(*this);    
}      

void C6Conf::Ok_clicked()
{
    Apply_clicked();
    done(0);
}

void C6Conf::SelFontUp_clicked()
{
    bool ok;

    QFont font = QFontDialog::getFont(&ok, QFont(FontStyle,FontSize,FontWeight), this) ;

    if (ok)
    {
        QFontInfo f(font);
        FontStyle = font.family();
        FontSize = font.pointSize();
        FontWeight = f.weight();
        updateChatPreview(ForegndColor,ForeNetFriendColorUp);      
    }
}

void C6Conf::contactSelFont_clicked()
{
    bool ok;
    QFont font = QFontDialog::getFont(&ok,QFont(contactFont.family,contactFont.size,
                                      contactFont.weight),this);

    if (ok)
    {
        QFontInfo f(font);
        contactFont.family = f.family();
        contactFont.size = f.pointSize();
        contactFont.weight = f.weight();

        updateFontText(contactFontProperty,f.family(),f.weight(),f.pointSize());
    }
}

void C6Conf::ForeColorUp_clicked()
{
    QColor color = QColorDialog::getColor(ForegndColor,this);

    if (color.isValid())
    {
        ForegndColor = color.name();
        updateChatPreview(ForegndColor,ForeNetFriendColorUp);
    }
}

void C6Conf::groupNameForeColor_clicked()
{
    QColor color = QColorDialog::getColor(contactGroupColor,this);

    if (color.isValid())
    {
        contactGroupColor = color.name();
        QColor color = QColor(contactGroupColor);
        groupColor->setPaletteBackgroundColor(color);
    }
}

void C6Conf::contactForeColor_clicked()
{
    QColor color = QColorDialog::getColor(contactUserColor,this);

    if (color.isValid())
    {
        contactUserColor = color.name();
        QColor color = QColor(contactUserColor);
        userColor->setPaletteBackgroundColor(color);
    }
}

void C6Conf::defaultContactClicked()
{
    contactUserColor = "#0376E7";
    contactGroupColor  = "#5C5C5C";
    QColor color(contactUserColor);
    userColor->setPaletteBackgroundColor(color);
    color =  QColor(contactGroupColor);
    groupColor->setPaletteBackgroundColor(color);

    if (contactFontSwitch->isChecked() == true)
    {
#if defined(Q_OS_MACX) || defined(Q_OS_DARWIN)
        contactFont.family =  "Lucida Grande";
        contactFont.size  = 12;
#else
        contactFont.family =  "Sans";
        contactFont.size  = 9;
#endif
        contactFont.weight  = QFont::Normal;
        updateFontText(contactFontProperty,contactFont.family,
                       contactFont.weight, contactFont.size);
    }
}

void C6Conf::Default_clicked()
{
#if defined(Q_OS_MACX) || defined(Q_OS_DARWIN)
    FontStyle = "Lucida Grande";
    FontSize = 12;
#else
    FontStyle = "Sans";
    FontSize = 10;
#endif
    ForegndColor = "#000060";
    FontWeight = QFont::Normal;
    ForeMessageColorUp = "#59A4FF";
    ForeNetFriendColorUp = "#FA3200";

    chatPreview->setFont(QFont(FontStyle,FontSize,FontSize));
    updateChatPreview(ForegndColor,ForeNetFriendColorUp);
    serviceMessagePreview->setPaletteForegroundColor(QColor(ForeMessageColorUp));    
}

void C6Conf::beepSwitch_clicked()
{
    if (beepSwitch->isChecked())
    {
        if (soundSwitch->isChecked())
        {
            soundSwitch->setChecked(false);
            soundGroup->setEnabled(false);
        }
    }
}

void C6Conf::soundSwitch_clicked()
{
    soundGroup->setEnabled(soundSwitch->isChecked());
    beepSwitch->setChecked(false);
}

void C6Conf::fileOpen1_clicked()
{
    QString tmp;

    tmp = fileOpen();
    if (tmp != "")
    {
        inMessageWav->setText(tmp);
    }
}

void C6Conf::fileOpen2_clicked()
{
    QString tmp;

    tmp = fileOpen();
    if (tmp != "")
    {
        outMessageWav->setText(tmp);
    }
}

void C6Conf::fileOpen3_clicked()
{
    QString tmp;

    tmp = fileOpen();
    if (tmp != "")
    {
        onlineMessageWav->setText(tmp);
    }
}

void C6Conf::fileOpen4_clicked()
{
    QString tmp;

    tmp = fileOpen();
    if (tmp != "")
    {
        offlineMessageWav->setText(tmp);
    }
}

QString C6Conf::fileOpen()
{
    return(QFileDialog::getOpenFileName(QDir::homeDirPath(),"Wav (*.wav)",this,""
                                        "Seleziona un file" ));
}

void C6Conf::fileOpen5_clicked()
{
    QString tmp;

    tmp = fileOpen();
    if (tmp != "")
    {
        specialFriendWav->setText(tmp);
    }
}

void C6Conf::addSpecial_clicked()
{
    C6Global &global = C6Global::getInstance();
    C6PixmapCache &pix = C6PixmapCache::getInstance();
    QString path = global.getSkinPath();
    QString tmp = specialEdit->displayText().stripWhiteSpace();
    QPixmap & qx = const_cast<QPixmap&>(pix.getPixmap(path+"bookmark2.png"));

    if (tmp != "")
    {
        if (!specialList->findItem(tmp))
        {
            specialList->insertItem(qx,tmp);
        }
        else
        {         
            QMessageBox::warning(this,"Attenzione",
                                 QString::fromUtf8("Il nick è gia presente in lista"),
                                 QMessageBox::Ok,QMessageBox::NoButton);
        }         
    }
}

void C6Conf::removeSpecial_clicked()
{
    specialList->removeItem(specialList->currentItem());
}

void C6Conf::saveSpecialList()
{
    QString home = QDir::homeDirPath();
    QFile file( home+"/"+C6DIR+"/special.lst" );

    int top=specialList->index(specialList->firstItem());

    if (file.open( IO_WriteOnly))
    {
        QTextStream stream( &file );

        for (int count=specialList->count(); count; count--)
            stream << specialList->text(top++)+"\n";

        file.close();
    }
}

void C6Conf::playDemo1_clicked()
{
    playWav(inMessageWav->displayText());
}

void C6Conf::playDemo2_clicked()
{
    playWav(outMessageWav->displayText ());
}

void C6Conf::playDemo3_clicked()
{
    playWav(onlineMessageWav->displayText());
}

void C6Conf::playDemo4_clicked()
{
    playWav(offlineMessageWav->displayText());
}

void C6Conf::playDemo5_clicked()
{
    playWav(specialFriendWav->displayText());
}

void C6Conf::ForeNetFriendUp_clicked()
{
    QColor color = QColorDialog::getColor(ForeNetFriendColorUp,this);

    if (color.isValid())
    {
        ForeNetFriendColorUp = color.name();
        updateChatPreview(ForegndColor,ForeNetFriendColorUp);
    }
}

void C6Conf::ForeMessageUp_clicked()
{
    QColor color = QColorDialog::getColor(ForeMessageColorUp,this);

    if (color.isValid())
    {
        ForeMessageColorUp = color.name();
        serviceMessagePreview->setPaletteForegroundColor(color);
    }
}

void C6Conf::updateChatPreview(QString const & myself,QString const & netfriend)
{
    chatPreview->clear();
    
    QString tmp = QString::fromUtf8("<othernickpre>[10:39:22] kernel.panic - </othernickpre>"
            "<text>ciao come va ?</text><br>"
            "<mynickpre>[10:40:00] gi0rgett0 - </mynickpre>"
            "<text>bene, grazie</text><br>"
            "<othernickpre>[10:39:22] kernel.panic - </othernickpre>"
            "<text>ti posso mandare un file ?</text><br>"
            "<mynickpre>[10:40:00] gi0rgett0 - </mynickpre>"                      
            "<text>certo la ricezione è gia attiva");
 
    QStyleSheet *sh=QStyleSheet::defaultSheet();
    
    sh->item("othernickpre")->setColor(QColor(netfriend));
    sh->item("othernickpre")->setFontFamily(FontStyle);
    sh->item("othernickpre")->setFontSize(FontSize);
    
    sh->item("mynickpre")->setColor(QColor(myself));
    sh->item("mynickpre")->setFontFamily(FontStyle);
    sh->item("mynickpre")->setFontSize(FontSize);
  
    chatPreview->setText(tmp);    
}


/*!
    \fn C6Conf::fileDir_clicked()
 */
void C6Conf::fileDir_clicked()
{
    QString ret;

    ret = QFileDialog::getExistingDirectory(QDir::homeDirPath(),this);
    if (ret)
    {
        fileReceivePath->setText(ret);
    }
}


/*!
    \fn C6Conf::postVariableSet()
 */
void C6Conf::postVariableSet()
{
    QString tmp;

    tmp = fileReceivePath->displayText();

    if (tmp != "")
    {
        if (tmp.at(tmp.length()-1) != '/')
        {
            fileReceivePath->setText(tmp+"/");
        }
    }
}


/*!
    \fn C6Conf::globalFontButton_clicked()
 */
void C6Conf::globalFontButton_clicked()
{
    bool ok;
    const QString family = globalFont.family;
    const int size = globalFont.size;
    const int weight = globalFont.weight;

    QFont font = QFontDialog::getFont(&ok,QFont(family,size,weight),this);

    if (ok == true)
    {
        QFontInfo f(font);
        globalFont.size = font.pointSize();
        globalFont.weight = f.weight();
        globalFont.family = font.family();
        updateFontText(fontProperty,globalFont.family,
                       globalFont.weight,globalFont.size);
    }
}


/*!
    \fn C6Conf::getFontInfo()
 */
C6Conf::FontInfo const & C6Conf::getFontInfo()
{
    return(globalFont);
}


/*!
    \fn C6Conf::selectFontButton_clicked()
 */
void C6Conf::selectFontButton_clicked()
{
    fontProperty->setEnabled(selectFontButton->isChecked());
    globalFontButton->setEnabled(selectFontButton->isChecked());
    defaultFontButton->setEnabled(selectFontButton->isChecked());
}


/*!
    \fn C6Conf::defaultFontButton_clicked()
 */
void C6Conf::defaultFontButton_clicked()
{
#if defined(Q_OS_MACX) || defined(Q_OS_DARWIN)
    globalFont.size = 12;
    globalFont.family = "Lucida Grande";
#else
    globalFont.size = 10;
    globalFont.family = "Sans";
#endif
    globalFont.weight = QFont::Normal;
    updateFontText(fontProperty,globalFont.family,globalFont.weight,globalFont.size);
}


/*!
    \fn C6Conf::updateGlobalFontText()
 */
void C6Conf::updateFontText(QLineEdit *line,QString const &family,
                            int weight,int size)
{
    line->setText(family+" ("+getFontWeightString(weight)+") "+
                  " ("+QString::number(size)+")");
}

void C6Conf::proxySwitch_toggled(bool status)
{
    serverName->setEnabled(!status);
    serverPort->setEnabled(!status);
    proxyName->setEnabled(status);
    proxyPort->setEnabled(status);
    proxyAuthBox->setEnabled(status);
    proxySocksVersion->setEnabled(status);
}


/*!
    \fn C6Conf::toggleAutoRoomList(bool enabled)
 */
void C6Conf::toggleAutoRoomList(bool enabled)
{
    autoRoomList->setEnabled(enabled);
}


/*!
    \fn C6Conf::toggleMessageEdit(bool)
 */
void C6Conf::toggleMessageEdit(bool enabled)
{
    AwayEdit->setEnabled(enabled);
    BlackListEdit->setEnabled(enabled);
    BusyEdit->setEnabled(enabled);
    NetFriendsEdit->setEnabled(enabled);
}


/*!
    \fn C6Conf::saveCurrentSettings()
 */
void C6Conf::saveCurrentSettings()
{
    QString str;
    C6Settings &settings = C6Settings::getInstance();

    if ((str=serverName->displayText().stripWhiteSpace()) != "")
        settings.setServerName(str);

    if ((str=serverPort->text().stripWhiteSpace()) != "")
        settings.setServerPort(str);

    if ((str=proxyName->displayText().stripWhiteSpace()) != "")
        settings.setProxyName(str);

    if ((str=proxyPort->text().stripWhiteSpace()) != "")
        settings.setProxyPort(str);

    if ((str=proxyUser->text().stripWhiteSpace()) != "")
        settings.setProxyUserId(str);

    if ((str=proxyPassword->text().stripWhiteSpace()) != "")
        settings.setProxyUserPsw(str);

    if ((str=BlackListEdit->displayText().stripWhiteSpace()) != "")
        settings.setBlackListMessage(str);

    if ((str=NetFriendsEdit->displayText().stripWhiteSpace()) != "")
        settings.setNetFriendsMessage(str);

    if ((str=BusyEdit->displayText().stripWhiteSpace()) != "")
        settings.setBusyMessage(str);

    if ((str=AwayEdit->displayText().stripWhiteSpace()) != "")
        settings.setAwayMessage(str);

    if ((str=Browser->displayText().stripWhiteSpace()) != "")
        settings.setBrowser(str);

    if ((str=fileReceivePath->displayText().stripWhiteSpace()) != "")
        settings.setFileReceivePath(str);

    settings.setAutoMessage(AutoMsg->isChecked());
    settings.setLog(Log->isChecked());
    settings.setAutoConnect(AutoConnect->isChecked());
    settings.setReconnect(Reconnect->isChecked());
    settings.setAutoRaise(AutoRaise->isChecked());
    settings.setAutoPopUp(AutoPopUp->isChecked());
    settings.setSysLog(SysLog->isChecked());
    settings.setShowOnline(ShowOnline->isChecked());
    settings.setStatus(startStatusSwitch->currentItem());
    settings.setSpecialNotifySwitch(specialNotifySwitch->isChecked());
    settings.setIpVisible(ipShow->isChecked());
    settings.setSoundSwitch(soundSwitch->isChecked());
    settings.setBeepSwitch(beepSwitch->isChecked());
    settings.setSpecialFriendSwitch(specialFriendSwitch->isChecked());
    settings.setInMessageWav(inMessageWav->displayText());
    settings.setOutMessageWav(outMessageWav->displayText());
    settings.setOnlineMessageWav(onlineMessageWav->displayText());
    settings.setOfflineMessageWav(offlineMessageWav->displayText());
    settings.setSpecialFriendWav(specialFriendWav->displayText());
    settings.setInMessageSwitch(inMessageSwitch->isChecked());
    settings.setOutMessageSwitch(outMessageSwitch->isChecked());
    settings.setOnlineMessageSwitch(onlineMessageSwitch->isChecked());
    settings.setOfflineMessageSwitch(offlineMessageSwitch->isChecked());
    settings.setSoundPlayer(playCommand->displayText());
    settings.setFontStyle(FontStyle);
    settings.setFontSize(FontSize);
    settings.setFontWeight(FontWeight);
    settings.setForegndColor(ForegndColor);
    settings.setForeMessageColor(ForeMessageColorUp);
    settings.setForeNetFriendColor(ForeNetFriendColorUp);
    settings.setDockIcon(dockIcon->isChecked());
    settings.setTimeStampSwitch(timeStamp->isChecked());
    settings.setStartPort(startPort->text());
    settings.setAutoAccept(autoAccept->isChecked());
    settings.setRoomTimeStamp(roomTimeStamp->isChecked());
    settings.setAutoRoomEnter(autoRoomEnter->isChecked());
    settings.setRoomLog(LogRoom->isChecked());
    settings.setProtoLog(LogProto->isChecked());
    settings.setSelectGlobalFont(selectFontButton->isChecked());

    const FontInfo &finfo = getFontInfo();
    settings.setGlobalFontSize(finfo.size);
    settings.setGlobalFontFamily(finfo.family);
    settings.setGlobalFontWeight(finfo.weight);
    settings.setTabbedChat(tabbedChat->isChecked());
    settings.setProxySwitch(proxySwitch->isChecked());
    settings.setAuthProxySwitch(proxyAuthSwitch->isChecked());
    settings.setLoginTimeout(maxTimeOut->value());
    settings.setContactFontSize(contactFont.size);
    settings.setContactFontFamily(contactFont.family);
    settings.setContactFontWeight(contactFont.weight);
    settings.setContactGroupForeColor(contactGroupColor);
    settings.setContactUserForeColor(contactUserColor);
    settings.setProxySocksVersion(proxySocksVersion->currentItem());
    settings.setAutoAway(autoAwaySwitch->isChecked());
    settings.setMinutesAway(awayMinutes->value());
    settings.setBackAutoAway(backAutoAwaySwitch->isChecked());
    settings.setContactFontSwitch(contactFontSwitch->isChecked());
    settings.setSoundOnce(soundOnceSwitch->isChecked());
    settings.setStyleSwitch(activateStyle->isChecked());
    settings.setWidgetStyle(styleCombo->currentText());    
    
    QStringList tmp;    
    for(int i=0; i < visualLocalFont->count(); i++)
    {
        tmp.append(visualLocalFont->text(i));     
    }          
    settings.setVisualChatFontStyle(tmp);
    
    settings.saveSettings();
    saveSpecialList();
    saveAutoRoomList();
    savePluginList();
}


/*!
    \fn C6Conf::loadSpecialList()
 */
void C6Conf::loadSpecialList()
{
    QString home = QDir::homeDirPath();
    QFile file( home+"/"+C6DIR+"/special.lst" );
    C6Global &global = C6Global::getInstance();
    QString path = global.getSkinPath();

    if (file.open( IO_ReadOnly))
    {
        QTextStream stream( &file );
        QString tmp;

        while ((tmp = stream.readLine()) != 0)
        {
            specialList->insertItem(
                C6PixmapCache::getInstance().getPixmap(path+"bookmark2.png"),tmp);
        }
        file.close();
    }
}


/*!
    \fn C6Conf::loadAutoRoomList()
 */
void C6Conf::loadAutoRoomList()
{
    QString home = QDir::homeDirPath();
    QFile roomList( home+"/"+C6DIR+"/autoroom.lst" );

    if (roomList.open( IO_ReadOnly))
    {
        QString tmp;
        QTextStream stream( &roomList );

        autoRoomList->setText(stream.read());
        roomList.close();
    }
}


/*!
    \fn C6Conf::loadPluginListAvailable()
 */
void C6Conf::loadPluginListAvailable()
{
    C6Global &global = C6Global::getInstance();
    QString pluginPath = global.getPluginPath();
    QDir dir(pluginPath);

    dir.setNameFilter("*.so");
    QStringList entries = dir.entryList();

    for (unsigned int i=0; i < entries.count(); i++)
    {
        (void*)new QListViewItem(pluginsAvailableList,pluginPath+entries[i]);
    }
}


/*!
    \fn C6Conf::insertPlugin()
 */
void C6Conf::insertPlugin()
{
    QListViewItem *pselected = pluginsAvailableList->selectedItem();
    if (pselected != 0)
    {
        C6Global &global = C6Global::getInstance();
        QString fname = pselected->text(0);

        C6AbstractPlugin *plugin = global.buildPlugin(fname,false);

        if (plugin != 0)
        {
            bool found = false;
            QListViewItemIterator it(pluginsLoadedList);

            for (; it.current(); ++it )
            {
                if (it.current()->text(1).compare(plugin->getName()) == 0)
                {
                    found = true;
                    break;
                }
            }

            if (found == false)
            {
                QString pluginName = plugin->getName();
                QString pluginDescr = plugin->getDescription();
                QString pluginKDE = (plugin->isForKde() == true) ? "Si" : "No";
                QString pluginActive = "No";

                (void*)new QListViewItem(pluginsLoadedList,fname.section("/",-1,-1),
                                         pluginName,pluginDescr,pluginKDE,pluginActive);

                global.unloadPlugin(fname);
            }
        }
    }
}


/*!
    \fn C6Conf::savePluginList()
 */
void C6Conf::savePluginList()
{
    QString home = QDir::homeDirPath();
    QFile file( home+"/"+C6DIR+"/plugin.lst" );
    C6Global &global = C6Global::getInstance();

    if (file.open( IO_WriteOnly))
    {
        QTextStream stream( &file );
        QListViewItemIterator it(pluginsLoadedList);

        for (; it.current(); ++it )
        {
            stream << global.getPluginPath() << it.current()->text(0) << "\n";
        }

        file.close();
    }
}



/*!
    \fn C6Conf::getLoadedPlugin()
 */
void C6Conf::getLoadedPlugin()
{
    C6Global &global = C6Global::getInstance();
    QStringList pname = global.getLoadedPlugin();

    for (unsigned int i=0; i < pname.count(); i++)
    {
        C6AbstractPlugin *plugin = global.getPluginInstance(pname[i]);
        if (plugin != 0)
        {
            QString pluginName = plugin->getName();
            QString pluginDescr = plugin->getDescription();
            QString pluginKDE = (plugin->isForKde() == true) ? "Si" : "No";

            (void*)new QListViewItem(pluginsLoadedList,pname[i].section("/",-1,-1),
                                     pluginName,pluginDescr,pluginKDE,"Si");

        }
    }
}

/*!
    \fn C6Conf::removePlugin()
 */
void C6Conf::removePlugin()
{
    QListViewItem *pselected =pluginsLoadedList->selectedItem();
    if (pselected != 0)
    {
        delete pselected;
    }

    savePluginList();
}


/*!
    \fn C6Conf::saveRoomList()
 */
void C6Conf::saveAutoRoomList()
{
    QString home = QDir::homeDirPath();
    QFile roomList( home+"/"+C6DIR+"/autoroom.lst" );

    if (roomList.open( IO_WriteOnly))
    {
        QTextStream stream( &roomList );

        stream << autoRoomList->text();

        roomList.close();
    }
}

void  C6Conf::contactFontToggled(bool toggle)
{
    contactFontProperty->setEnabled(toggle);
    contactSelFont->setEnabled(toggle);
}

void  C6Conf::setStyleCombo(QString const & style)
{
    for(int i=0; i < styleCombo->count(); i++)
    {
        if (styleCombo->text(i).compare(style) == 0)
        {
            styleCombo->setCurrentItem(i);
            break;
        }         
    }      
}      
       


/*!
    \fn C6Conf::Cancel_clicked()
 */
void C6Conf::Cancel_clicked()
{
    done(0);
}


void C6Conf::setConfigurationMode(C6XCAPClient::CONFIG_MODE mode)
{
    authGroup->setEnabled(true);   
    noAuthButton->setChecked(false);
    warnAuthButton->setChecked(false);        
    askAuthButton->setChecked(false);      
          
    switch (mode) 
    {
        case C6XCAPClient::NOWARN:
            noAuthButton->setChecked(true);         
            break;
        case C6XCAPClient::WARN:
            warnAuthButton->setChecked(true);          
            break;
        case C6XCAPClient::PERMISSION:
            askAuthButton->setChecked(true);      
            break;
        default:
            break;
    }           
}
      
void C6Conf::setOfflineMode(C6XCAPClient::OFFLINE_MODE mode)
{
    messageGroup->setEnabled(true);     
    emailButton->setChecked(false);
    reportButton->setChecked(false);
          
    switch(mode)
    {
        case C6XCAPClient::EMAIL:
            emailButton->setChecked(true);         
            break;
        case C6XCAPClient::REPORT:
            reportButton->setChecked(true);
            break;
        default:
            break;                                             
    }         
}
      
C6XCAPClient::CONFIG_MODE C6Conf::getConfigurationMode()
{
    C6XCAPClient::CONFIG_MODE ret = C6XCAPClient::UNDEFINED_CONFIG;
      
    if (noAuthButton->isChecked() == true)
    {
        ret = C6XCAPClient::NOWARN;    
    }
    else
    {              
        if (warnAuthButton->isChecked() == true)
        {
            ret = C6XCAPClient::WARN; 
        }
        else
        {                                
            ret = C6XCAPClient::PERMISSION;
        }         
    }    
    return(ret);     
}      

C6XCAPClient::OFFLINE_MODE C6Conf::getOfflineMode()
{
    C6XCAPClient::OFFLINE_MODE ret = C6XCAPClient::UNDEFINED_OFFLINE;    
        
    if (emailButton->isChecked() == true)
    {
        ret = C6XCAPClient::EMAIL;
    }
    else
    {                 
        ret = C6XCAPClient::REPORT;
    }      
    
    return(ret);   
}      

/*!
    \fn C6Conf::loadVisualFontStyle()
 */
void C6Conf::loadVisualFontStyle()
{
    C6Settings &settings = C6Settings::getInstance();
    const QStringList& list = settings.getVisualChatFontStyle();   
    C6PixmapCache &pix = C6PixmapCache::getInstance();
    QString path = C6Global::getInstance().getSkinPath();
    
    visualLocalFont->insertStringList(list);  
    checkFontAvailability(list);
    visualLocalFont->setCurrentItem(0);    
}


/*!
    \fn C6Conf::mapFontSelectionClicked()
 */
void C6Conf::mapFontSelectionClicked()
{
    bool ok;
    QString currentFont = visualLocalFont->currentText();
        
    if (currentFont != QString::null && currentFont.length() > 0)
    {          
        QFont font = QFontDialog::getFont(&ok, QFont(currentFont),this);

        if (ok == true)
        {
            visualLocalFont->changeItem(font.family(),visualLocalFont->currentItem());     
        }
    }         
}


/*!
    \fn C6Conf::defaultListButtonClicked();
 */
void C6Conf::defaultListButtonClicked()
{
    QStringList tmp = C6Settings::getInstance().getDefaultVisualChatFontStyle();
    visualLocalFont->clear();    
    visualLocalFont->insertStringList(tmp);  
    checkFontAvailability(tmp);       
}


/*!
    \fn C6Conf::checkFontAvailability()
 */
void C6Conf::checkFontAvailability(QStringList const& list)
{
    C6Settings &settings = C6Settings::getInstance();
    C6PixmapCache &pix = C6PixmapCache::getInstance();
    QString path = C6Global::getInstance().getSkinPath();   
    QFontDatabase fontDatabase;  
    QStringList families = fontDatabase.families();
        
    for (unsigned int i=0; i < list.count(); i++)
    {
        QStringList splitted = QStringList::split(" ",list[i]);        
        bool found = false;    
        
        for (unsigned int j=0; j < splitted.count() && found == false; j++)
        {
            for (unsigned int k=0; k < families.count(); k++)
            {
                if (families[k].contains(splitted[j]))
                {
                    found = true;     
                }                   
            }                
        }             
        
        if (found == false)
        {
            visualLocalFont->changeItem(pix.getPixmap(path+"flag.png"),visualLocalFont->text(i),i);
        }             
    }          
}
