/***************************************************************************
                          settingsdialog.cpp  -  description
                             -------------------
    begin                : Sat Jan 11 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 "settingsdialog.h"

#include <qbuttongroup.h>
#include <qcheckbox.h>
#include <qcstring.h>
#include <qcolor.h>
#include <qcombobox.h>
#include <qfont.h>
#include <qframe.h>
#include <qlabel.h>
#include <qlayout.h>
#include <qpixmap.h>
#include <qradiobutton.h>
#include <qregexp.h>
#include <qtextedit.h>
#include <qtoolbutton.h>

#include <kapp.h>
#include <kcolorbutton.h>
#include <kconfig.h>
#include <kdebug.h>
#include <kdirselectdialog.h>
#include <kfiledialog.h>
#include <kfontdialog.h>
#include <kglobal.h>
#include <kiconloader.h>
#include <klineedit.h>
#include <klocale.h>
#include <kmessagebox.h>
#include <knuminput.h>
#include <kpassdlg.h>
#include <kpushbutton.h>
#include <kstandarddirs.h>
#include <ktextbrowser.h>
#include <kurl.h>

#include "../account.h"
#include "../emoticoncollection.h"
#include "../kmessdebug.h"
#include "accountswidget.h"
#include "alertswidget.h"
#include "chattingwidget.h"
#include "chatloggingwidget.h"
#include "emailwidget.h"
#include "proxywidget.h"
#include "imagewidget.h"

// The constructor
SettingsDialog::SettingsDialog(QWidget *parent, const char *name )
  : KDialogBase( IconList, i18n("Settings"), Help | Ok | Apply | Cancel | User1, Ok, parent, name, false, true, i18n( "&Delete" ) ),
    account_(0)
{
  KIconLoader   *loader = KGlobal::iconLoader();
  KStandardDirs *dirs   = KGlobal::dirs();
  QPixmap        pixmap;

  // Create the various widgets
  config_ = kapp->config();
  // Load the options from the configuration file
  readOptions();

  // "Manually" set up the look of the dialog.
  QFrame    *accountsFrame = addPage( i18n( "Accounts" ),     i18n( "Accounts" ),           loader->loadIcon( "identity",     KIcon::NoGroup, KIcon::SizeMedium ) );
  QFrame       *imageFrame = addPage( i18n( "Display pic" ),  i18n( "Display pic" ),        loader->loadIcon( "icons",        KIcon::NoGroup, KIcon::SizeMedium ) );
  QFrame      *alertsFrame = addPage( i18n( "Alerts" ),       i18n( "Alerts" ),             loader->loadIcon( "date" ,        KIcon::NoGroup, KIcon::SizeMedium ) );
  QFrame    *chattingFrame = addPage( i18n( "Chatting" ),     i18n( "Chatting" ),           loader->loadIcon( "fonts" ,       KIcon::NoGroup, KIcon::SizeMedium ) );
  QFrame *chatLoggingFrame = addPage( i18n( "Chat Logging" ), i18n( "Chat Logging" ),       loader->loadIcon( "filesaveas" ,  KIcon::NoGroup, KIcon::SizeMedium ) );
  QFrame       *emailFrame = addPage( i18n( "Email" ),        i18n( "Email Notification") , loader->loadIcon( "mail_generic", KIcon::NoGroup, KIcon::SizeMedium ) );
  QFrame       *proxyFrame = addPage( i18n( "Proxy" ),        i18n( "Proxy")              , loader->loadIcon( "proxy",        KIcon::NoGroup, KIcon::SizeMedium ) );
  
  // Create the layouts
  QVBoxLayout    *accountsLayout = new QVBoxLayout(    accountsFrame );
  QVBoxLayout       *imageLayout = new QVBoxLayout(       imageFrame );
  QVBoxLayout      *alertsLayout = new QVBoxLayout(      alertsFrame );
  QVBoxLayout    *chattingLayout = new QVBoxLayout(    chattingFrame );
  QVBoxLayout *chatLoggingLayout = new QVBoxLayout( chatLoggingFrame );
  QVBoxLayout       *emailLayout = new QVBoxLayout(       emailFrame );
  QVBoxLayout       *proxyLayout = new QVBoxLayout(       proxyFrame );

  // Create the widgets that belong in the frames
     accountsWidget_ = new    AccountsWidget(    accountsFrame , "accounts" );
     imageWidget_ = new       ImageWidget(       imageFrame,  "image"   );
       alertsWidget_ = new      AlertsWidget(      alertsFrame,  "alerts"   );
     chattingWidget_ = new    ChattingWidget(    chattingFrame , "chatting" );
  chatLoggingWidget_ = new ChatLoggingWidget( chatLoggingFrame , "chatLogging" );
        emailWidget_ = new       EmailWidget(       emailFrame,  "email"   );
        proxyWidget_ = new       ProxyWidget(       proxyFrame,  "proxy"   );

  // Add the widgets to the layouts
     accountsLayout->addWidget(    accountsWidget_ );
     imageLayout->addWidget(       imageWidget_ );
       alertsLayout->addWidget(      alertsWidget_ );
     chattingLayout->addWidget(    chattingWidget_ );
  chatLoggingLayout->addWidget( chatLoggingWidget_ );
        emailLayout->addWidget(       emailWidget_ );
        proxyLayout->addWidget(       proxyWidget_ );
        
  // Connect the timer widget's notification checkbox
  connect( alertsWidget_->useNotifierCheckBox_,     SIGNAL(                 toggled(bool) ),
           this,                                    SLOT  ( useNotificationsToggled(bool) ) );
  // Connect the profile's font button to the fontClicked slot
  connect( chattingWidget_->useContactFontCheckBox_,SIGNAL(                 toggled(bool) ),
           this,                                    SLOT  (   useContactFontToggled(bool) ) );
  connect( chattingWidget_->fontButton_,            SIGNAL(                 clicked()     ),
           this,                                    SLOT  (             fontClicked()     ) );
  connect( chattingWidget_->contactFontButton_,     SIGNAL(                 clicked()     ),
           this,                                    SLOT  (      contactFontClicked()     ) );
  connect( chattingWidget_->previewButton_,         SIGNAL(                 clicked()     ),
           this,                                    SLOT  (          previewClicked()     ) );
  connect( chattingWidget_->timeButton_,            SIGNAL(                 clicked()     ),
           this,                                    SLOT  (              insertTime()     ) );
  connect( chattingWidget_->nameButton_,            SIGNAL(                 clicked()     ),
           this,                                    SLOT  (              insertName()     ) );
  connect( chattingWidget_->messageButton_,         SIGNAL(                 clicked()     ),
           this,                                    SLOT  (           insertMessage()     ) );
  connect( chattingWidget_->resetButton_,           SIGNAL(                 clicked()     ),
           this,                                    SLOT  (             resetFormat()     ) );
  // Connect the directory button to open a directory selecting dialog
  connect( chatLoggingWidget_->chatSavePathButton_, SIGNAL(                 clicked()     ),
           this,                                    SLOT  (         chooseDirectory()     ) );
  chatLoggingWidget_->chatSavePathEdit_->setReadOnly( true );

  // Set up the emoticons in the "chatting" widget
  pixmap.load( dirs->findResource( "data", "kmess/emoticons/teeth.png" ) );
  chattingWidget_->pixmapLabel1_->setPixmap( pixmap );
  pixmap.load( dirs->findResource( "data", "kmess/emoticons/rainbow.png" ) );
  chattingWidget_->pixmapLabel2_->setPixmap( pixmap );
  pixmap.load( dirs->findResource( "data", "kmess/emoticons/dog.png" ) );
  chattingWidget_->pixmapLabel3_->setPixmap( pixmap );
}



// The destructor
SettingsDialog::~SettingsDialog()
{
  saveOptions();
#ifdef KMESSDEBUG_SETTINGSDIALOG
  kdDebug() << "DESTROYED SettingsDialog " << endl;
#endif
}



// Show the settings dialog for the given account
void SettingsDialog::changeAccountSettings(Account *account, bool isCurrentAccount)
{
  account_ = account;
  if ( account != 0 )
  {
    // Load account information into the widgets
    loadAccountsSettings( account, isCurrentAccount );
    loadAlertsSettings( account );
    loadChattingSettings( account );
    loadChatLoggingSettings( account );
    loadEmailSettings( account );
    loadProxySettings( account );
    loadImageSettings( account );
    exec();
  }
}



// Get a directory from the user.
void SettingsDialog::chooseDirectory()
{
  QString startDir, dir;

  startDir = chatLoggingWidget_->chatSavePathEdit_->text();

  dir = KFileDialog::getExistingDirectory( startDir );

  if ( dir != "" )
  {
    chatLoggingWidget_->chatSavePathEdit_->setText( dir );
  }
}



// Save options before closing.
void SettingsDialog::closeEvent(QCloseEvent *event)
{
  saveOptions();
  event->accept();
}



// The contact font button was pressed.  Show a font dialog to get a new font.
void SettingsDialog::contactFontClicked()
{
  QFont   font;
  QString fontFamily;
  bool    accepted;

  // Get a default font from the font button
  fontFamily = chattingWidget_->contactFontButton_->text().replace("&",QString::null);
  font = chattingWidget_->contactFontButton_->font();
  // Get a new font and font family from the user
  accepted = getFont( font, fontFamily );
  // If it was accepted, set the font to the button
  if ( accepted )
  {
    chattingWidget_->contactFontButton_->setText( fontFamily );
    chattingWidget_->contactFontButton_->setFont( font );
  }
}



// The font button was pressed.  Show a font dialog to get a new font.
void SettingsDialog::fontClicked()
{
  QFont   font;
  QString fontFamily;
  bool    accepted;

  // Get a default font from the font button
  fontFamily = chattingWidget_->fontButton_->text().replace("&",QString::null);
  font = chattingWidget_->fontButton_->font();
  // Get a new font and font family from the user
  accepted = getFont( font, fontFamily );
  // If it was accepted, set the font to the button
  if ( accepted )
  {
    chattingWidget_->fontButton_->setText( fontFamily );
    chattingWidget_->fontButton_->setFont( font );
  }
}



// Get a font and cleaned-up font family from a dialog
bool SettingsDialog::getFont(QFont &font, QString &fontFamily) const
{
  bool  accepted;
  int   leftBracket, result;
  QFont selection;

  selection = font;

  result = KFontDialog::getFont( selection );
  accepted = ( result == KFontDialog::Accepted );

  if ( accepted )
  {
    fontFamily = selection.family();
    // KDE3 seems to want to throw some stuff in square brackets at the
    //  end of font names.  Strip that stuff off.
    // I'm assuming no real proper font has "[" in the name.
    leftBracket = fontFamily.find( "[" );
    if ( leftBracket >= 0 )
    {
      fontFamily = fontFamily.left( leftBracket );
    }
    fontFamily = fontFamily.stripWhiteSpace();
    font = selection;
  }
  return accepted;
}



// Insert the {message} placeholder into the format box
void SettingsDialog::insertMessage()
{
  insertPlaceholder( i18n("message") );
}



// Insert the {name} placeholder into the format box
void SettingsDialog::insertName()
{
  insertPlaceholder( i18n("name") );
}



// Insert the given placeholder into the format box
void SettingsDialog::insertPlaceholder(const QString& placeholder)
{
  chattingWidget_->formatEdit_->insert( "{" + placeholder + "}" );
}



// Insert the {time} placeholder into the format box
void SettingsDialog::insertTime()
{
  insertPlaceholder( i18n("time") );
}



// Load account information into the account widget
void SettingsDialog::loadAccountsSettings(Account *account, bool isCurrentAccount)
{
  accountsWidget_->autologinCheckBox_->setChecked( account->getUseAutologin() );
  accountsWidget_->friendlyNameEdit_->setText( account->getFriendlyName() );
  accountsWidget_->handleEdit_->setText( account->getHandle() );
  accountsWidget_->passwordEdit_->setText("");
  accountsWidget_->startInvisibleCheckBox_->setChecked( account->getStartInvisible() );
  // The friendly name edit should only be enabled if this is the current account
  if ( isCurrentAccount )
  {
    accountsWidget_->friendlyNameEdit_->setEnabled( true );
  }
  else
  {
    accountsWidget_->friendlyNameEdit_->setEnabled( false );
  }
}



// Load account information into the alerts widget
void SettingsDialog::loadAlertsSettings(Account *account)
{
  alertsWidget_->useIdleTimerCheckBox_->setChecked( account->getUseIdleTimer() );
  alertsWidget_->idleTimeSpinBox_->setValue( account->getIdleTime() );
  alertsWidget_->useNotifierCheckBox_->setChecked( account->getUseNotifier() );
  alertsWidget_->notificationDurationSpinBox_->setValue( account->getNotificationDuration() );
  alertsWidget_->showOfflineNotificationsCheckBox_->setChecked( account->getShowOfflineNotification() );
  useNotificationsToggled( account->getUseNotifier() );
}



// Load account information into the chatting widget
void SettingsDialog::loadChattingSettings(Account *account)
{
  QColor color;
  QFont  font;

  // Set up the values
  color.setNamedColor( account->getFontColor() );
  font = account->getFont();

  chattingWidget_->fontButton_->setText( font.family() );
  chattingWidget_->fontButton_->setFont( font );
  chattingWidget_->fontColorButton_->setColor( color );

  color.setNamedColor( account->getContactFontColor() );
  font = account->getContactFont();

  chattingWidget_->contactFontButton_->setText( font.family() );
  chattingWidget_->contactFontButton_->setFont( font );
  chattingWidget_->contactFontColorButton_->setColor( color );

  chattingWidget_->useContactFontCheckBox_->setChecked( account->getUseContactFont() );
  useContactFontToggled( account->getUseContactFont() );
  chattingWidget_->useEmoticonsCheckBox_->setChecked( account->getUseEmoticons() );
  chattingWidget_->useFontEffectsCheckBox_->setChecked( account->getUseFontEffects() );
  chattingWidget_->formatEdit_->setText( account->getChatFormat() );
}



// Load account information into the chat logging widget
void SettingsDialog::loadChatLoggingSettings(Account *account)
{
  chatLoggingWidget_->logChatsCheckBox_->setChecked( account->getSaveChats() );
  chatLoggingWidget_->chatSavePathEdit_->setText( account->getSaveChatPath() );

  switch(account->getSavedChatDirectoryStructure())
  {
    case Account::SINGLEDIRECTORY :
    {
      chatLoggingWidget_->singleDirectoryRadioButton_->setChecked( true );
      break;
    }
    case Account::BYYEAR :
    {
      chatLoggingWidget_->yearRadioButton_->setChecked( true );
      break;
    }
    case Account::BYMONTH :
    {
      chatLoggingWidget_->monthRadioButton_->setChecked( true );
      break;
    }
    case Account::BYDAY :
    {
      chatLoggingWidget_->dayRadioButton_->setChecked( true );
      break;
    }
  }
}



// Load account information into the email widget
void SettingsDialog::loadEmailSettings(Account *account)
{
  emailWidget_->useHotmailRadioButton_->setChecked( account->getUseHotmail() );
  emailWidget_->useCommandRadioButton_->setChecked( !account->getUseHotmail() );
  emailWidget_->emailCommandEdit_->setText( account->getEmailCommand() );
  emailWidget_->showEmailInfoCheckBox_->setChecked( account->getShowEmail() );
  emailWidget_->showOtherFoldersCheckBox_->setChecked( account->getShowOtherFolders() );

  // TODO: find out whether this always appears to be true
  emailWidget_->clientButtonGroup_       ->setEnabled(account->getEmailSupported());
  emailWidget_->notificationButtonGroup_ ->setEnabled(account->getEmailSupported());
}


// Load account information into the proxy widget
void SettingsDialog::loadProxySettings(Account *account)
{
    proxyWidget_->loadProxySettings(account);
}

void SettingsDialog::loadImageSettings(Account *account)
{
  imageWidget_->loadSettings( account );
}

// Do some effects characters (ie, bold, underline and italic specials)
void SettingsDialog::parseEffects(QString &text) const
{
  int       offset = 0, effectsNumber;
  bool      startFree, endFree;
  QRegExp   effectsSearch;
  QString   effectsCharacter, markupString;
  QChar     boundaryCharacter;

  for (effectsNumber = 0; effectsNumber < 3; effectsNumber++)
  {
    switch( effectsNumber )
    {
      case 0:
        effectsCharacter = "_";
        markupString = "u";
        break;
      case 1:
        effectsCharacter = "\\*";
        markupString = "b";
        break;
      case 2:
        effectsCharacter = "/";
        markupString = "i";
        break;
    }

    effectsSearch.setPattern( effectsCharacter + "([a-zA-Z0-9]+)" + effectsCharacter );

    offset = 0;

    while( offset >= 0 )
    {
      offset = effectsSearch.search( text, offset );

      if( offset >= 0 )
      {

        startFree = endFree = false;

        if ( offset == 0 )
        {
          startFree = true;
        }
        else
        {
          boundaryCharacter = text.at( offset - 1 );
          if ( boundaryCharacter.isSpace() || boundaryCharacter.isPunct() ) startFree = true;
        }

        if ( ( offset + effectsSearch.matchedLength() ) == text.length() )
        {
          endFree = true;
        }
        else
        {
          boundaryCharacter = text.at( offset + effectsSearch.matchedLength() );
          if ( boundaryCharacter.isSpace() || boundaryCharacter.isPunct() ) endFree = true;
        }

        if ( startFree && endFree )
        {
          text.replace( offset, 1, "<" + markupString + ">");
          text.replace( offset + effectsSearch.matchedLength() + markupString.length(), 1, "</" + markupString + ">");
        }
      }

      offset+= effectsSearch.matchedLength();
    }
  }
}



// Parse a message, using simple rules, to show a preview of the chat
QString SettingsDialog::parseMessage( QString name, QString message, const QString& format, bool isUser )
{
#ifdef KMESSDEBUG_SETTINGSDIALOG
  kdDebug() << "SettingsDialog - Parse the example message." << endl;
#endif
  QString              fontColor, parsedMessage, nameColor, formattedTime, formattedMessage;
  QFont                font;
  QTime                time;
  EmoticonCollection  *emoticons_;

  emoticons_ = EmoticonCollection::instance();

  if ( isUser )
  {
    // Get the user's specified font
    font = chattingWidget_->fontButton_->font();
    fontColor = chattingWidget_->fontColorButton_->color().name();
    // Format the name using the color for users
    nameColor = "#006A00";
    // Set the time
    time.setHMS( 8, 25, 14 );
  }
  else
  {
    // Check if we should use a specified contact font
    if ( chattingWidget_->useContactFontCheckBox_->isChecked() )
    {
      // Get the specified font
      font = chattingWidget_->contactFontButton_->font();
      fontColor = chattingWidget_->contactFontColorButton_->color().name();
    }
    else
    {
      // Use some picked font for the contact
      font.setFamily("Arial");
      fontColor = "FF1A5B";
    }
    // Format the name using the color for contacts
    nameColor = "#D60000";
    // Set the time - earlier, since the contact's message goes first
    time.setHMS( 8, 24, 39 );
  }

  if ( chattingWidget_->useEmoticonsCheckBox_->isChecked() )
  {
    // Parse the name and message for emoticons
    emoticons_->parseEmoticons( name );
    emoticons_->parseEmoticons( message );
  }

  if ( chattingWidget_->useFontEffectsCheckBox_->isChecked() )
  {
     parseEffects( message );
  }

  // Format the message using the font and color specified
  formattedMessage = "";
  if ( font.bold() )
    formattedMessage += "<b>";
  if ( font.italic() )
    formattedMessage += "<i>";
  if ( font.underline() )
    formattedMessage += "<u>";

  formattedMessage += "<font face=\"" + font.family() + "\" color=\"" + fontColor + "\" >" + message + "</font>";

  if ( font.underline() )
    formattedMessage += "</u>";
  if ( font.italic() )
    formattedMessage += "</i>";
  if ( font.bold() )
    formattedMessage += "</b>";

  formattedTime = KGlobal::locale()->formatTime( time, true );
  formattedTime = formattedTime;


  parsedMessage = format;
  parsedMessage = parsedMessage.replace( QRegExp("\n"), "<br>" );

  parsedMessage = parsedMessage.replace( QRegExp("\\{" + i18n( "time" ) +     "\\}"), formattedTime );
  parsedMessage = parsedMessage.replace( QRegExp("\\{" + i18n( "name" ) +     "\\}"), name );
  parsedMessage = parsedMessage.replace( QRegExp("\\{" + i18n( "message" ) +  "\\}"), formattedMessage );
  parsedMessage = parsedMessage.replace( QRegExp("  "), "&nbsp;&nbsp;" );
  parsedMessage = "<font color=" + nameColor + ">" + parsedMessage + "</font>";
  return parsedMessage;
}



// The "preview" button was pressed.  Preview the chat format.
void SettingsDialog::previewClicked()
{
  QString chatFormat, chatText, userName, contactName, fakeMessage1, fakeMessage2;
  // Get the user's name
  userName = accountsWidget_->friendlyNameEdit_->text();
  // Set the chatted-with contact's name
  contactName = i18n("Stacy");
  // Set the messages that the previewed chatters will be saying
  fakeMessage1 = i18n("Aren't you going to open your gift? :)");
  fakeMessage2 = i18n("If it's a severed head, I'll be /really/ upset.");
  // Get the format of the chat
  chatFormat = chattingWidget_->formatEdit_->text();

  // Append each parsed message to the chat text
  chatText =  parseMessage( contactName, fakeMessage1, chatFormat, false );
  chatText += "<br>";
  chatText += parseMessage( userName,    fakeMessage2, chatFormat, true );

  // Show the text
  chattingWidget_->previewBrowser_->setText( chatText );
}



// Save account information from the proxy widget
void SettingsDialog::saveProxySettings(Account *account)
{
    bool useproxy = proxyWidget_->useProxyCheckBox_->isChecked();
    int  proxytype = proxyWidget_->proxyTypeComboBox_->currentItem();
    QString proxyserver = proxyWidget_->serverLineEdit_->text();
    QString proxyuid = proxyWidget_->uidLineEdit_->text();
    QString proxypassword=proxyWidget_->passwordLineEdit_->text();
    int proxyport = proxyWidget_->portSpinBox_->value();

    account->setProxyInformation(useproxy, proxytype,proxyserver,proxyport,proxyuid,proxypassword);
}

void SettingsDialog::saveImageSettings(Account *account)
{
  imageWidget_->saveSettings(account);
}

// Read options from the configuration file.
void SettingsDialog::readOptions()
{
  // Pull in the window size and position
  config_->setGroup("SettingsDialog");
  QSize size = config_->readSizeEntry("Size");
  if(!size.isEmpty())
  {
    resize(size);
  }
  QPoint pos = config_->readPointEntry("Position");
  if(!pos.isNull())
  {
    move(pos);
  }
}



// Reset the message format to the default
void SettingsDialog::resetFormat()
{
  chattingWidget_->formatEdit_->setText( i18n("{time} {name} says:\n{message}\n") );
  previewClicked();
}



// Save all widget settings
void SettingsDialog::saveAccountSettings()
{
  if ( account_ != 0 )
  {
    // Save information from the widgets
    saveAccountsSettings( account_ );
    saveAlertsSettings( account_ );
    saveChattingSettings( account_ );
    saveChatLoggingSettings( account_ );
    saveEmailSettings( account_ );
    saveProxySettings( account_ );
    saveImageSettings( account_ );
  }
}




// Save account information from the account widget
void SettingsDialog::saveAccountsSettings(Account *account)
{
  QString password;

  password = accountsWidget_->passwordEdit_->password();

  account->setLoginInformation( accountsWidget_->handleEdit_->text(), accountsWidget_->friendlyNameEdit_->text(), password );
  account->setUseAutologin( accountsWidget_->autologinCheckBox_->isChecked() );
  account->setStartInvisible( accountsWidget_->startInvisibleCheckBox_->isChecked() );
}



// Save account information from the alerts widget
void SettingsDialog::saveAlertsSettings(Account *account)
{
  account->setAlertsInformation( alertsWidget_->useIdleTimerCheckBox_->isChecked(),
                                 alertsWidget_->idleTimeSpinBox_->value(),
                                 alertsWidget_->useNotifierCheckBox_->isChecked(),
                                 alertsWidget_->notificationDurationSpinBox_->value(),
                                 alertsWidget_->showOfflineNotificationsCheckBox_->isChecked() );
}



// Save account information from the chatting widget
void SettingsDialog::saveChattingSettings(Account *account)
{
   QFont font, contactFont;

  font = chattingWidget_->fontButton_->font();
  font.setFamily( chattingWidget_->fontButton_->text() );

  contactFont = chattingWidget_->contactFontButton_->font();
  contactFont.setFamily( chattingWidget_->contactFontButton_->text() );

  account->setFontInformation( font, chattingWidget_->fontColorButton_->color().name(),
                               contactFont, chattingWidget_->contactFontColorButton_->color().name() );

  account->setChatInformation( chattingWidget_->useContactFontCheckBox_->isChecked(),
                               chattingWidget_->useEmoticonsCheckBox_->isChecked(),
                               chattingWidget_->useFontEffectsCheckBox_->isChecked(),
                               chattingWidget_->formatEdit_->text() );
}



// Save account information from the chat logging widget
void SettingsDialog::saveChatLoggingSettings(Account *account)
{
  int directoryStructure = Account::SINGLEDIRECTORY;

  if ( chatLoggingWidget_->singleDirectoryRadioButton_->isChecked() )
  {
    directoryStructure = Account::SINGLEDIRECTORY;
  }
  else if ( chatLoggingWidget_->yearRadioButton_->isChecked() )
  {
    directoryStructure = Account::BYYEAR;
  }
  else if ( chatLoggingWidget_->monthRadioButton_->isChecked() )
  {
    directoryStructure = Account::BYMONTH;
  }
  else if ( chatLoggingWidget_->dayRadioButton_->isChecked() )
  {
    directoryStructure = Account::BYDAY;
  }
  account->setChatLoggingInformation( chatLoggingWidget_->logChatsCheckBox_->isChecked(),
                                      chatLoggingWidget_->chatSavePathEdit_->text(),
                                      directoryStructure );

}



// Save account information from the email widget
void SettingsDialog::saveEmailSettings(Account *account)
{
  account->setEmailInformation( emailWidget_->useHotmailRadioButton_->isChecked(),
                                emailWidget_->emailCommandEdit_->text(),
                                emailWidget_->showEmailInfoCheckBox_->isChecked(),
                                emailWidget_->showOtherFoldersCheckBox_->isChecked() );
}



// Save the options.
void SettingsDialog::saveOptions()
{
  // Save the window geometry
  config_->setGroup("SettingsDialog");
  config_->writeEntry("Size", size());
  config_->writeEntry("Position", pos());
}



// The apply button was clicked.  Apply the changes.
void SettingsDialog::slotApply()
{
  saveAccountSettings();
}



// The cancel button was clicked.  Close the dialog.
void SettingsDialog::slotCancel()
{
  reject();
}



// The OK button was pressed.  Apply the changes and close.
void SettingsDialog::slotOk()
{
  saveAccountSettings();
  accept();
}



// The delete button was pressed.
void SettingsDialog::slotUser1()
{
  // Ask the user for confirmation
  if ( ( KMessageBox::warningYesNo( this, i18n("Are you sure you want to delete this account?")) ) == KMessageBox::Yes )
  {
    emit deleteAccount( account_ );
    reject();
  }
}



// Enable or disable the contact font and color selectors.
void SettingsDialog::useContactFontToggled(bool checked)
{
  chattingWidget_->contactFontButton_->setEnabled( checked );
  chattingWidget_->contactFontColorButton_->setEnabled( checked );
}



// Enable or disable the sub-notification depending on the overall
//  notification.
void SettingsDialog::useNotificationsToggled(bool checked)
{
  alertsWidget_->showOfflineNotificationsCheckBox_->setEnabled( checked );
}

#include "settingsdialog.moc"
