/***************************************************************************
                          addcontactdialog.cpp  -  description
                             -------------------
    begin                : Sun Apr 14 2002
    copyright            : (C) 2002 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 "addcontactdialog.h"

#include "../contact/group.h"
#include "../model/contactlist.h"
#include "../utils/kmessconfig.h"
#include "../currentaccount.h"
#include "../kmessdebug.h"



/**
 * Constructor
 *
 * The dialog is instantly shown as modal when the class is instantiated.
 *
 * @param handle       Reference to the handle of the contact to add
 * @param groupsId     Reference to the added contact's initial groups
 * @param parent       Parent widget
 */
AddContactDialog::AddContactDialog( QString &handle, QStringList &groupsId, QWidget *parent )
: KDialog( parent )
, Ui::AddContactDialog()
{
  // Set up the interface and the dialog
  setObjectName( "AddContact" );
  QWidget *mainWidget = new QWidget( this );
  setupUi( mainWidget );
  setMainWidget( mainWidget );

  // Configure the dialog
  setWindowModality( Qt::WindowModal );
  setCaption( i18n("Add a Contact") );
  setButtons( Ok | Cancel );
  setDefaultButton( Ok );

  // Connect the signals to check dialog's input
  connect( emailAddressEdit_, SIGNAL(         textChanged(const QString&) ),
           this,              SLOT  (    interfaceChanged()               ) );

  // Lock the dialog height, it's ugly otherwise
  restoreDialogSize( KMessConfig::instance()->getGlobalConfig( "AddContactDialog" ) );

  icon_->setPixmap( KIcon( "list-add-user" ).pixmap( 48, 48 ) );

  // Fill up the groups list from the contactlist data
  const QList< Group* >& groupList( CurrentAccount::instance()->getContactList()->getGroupList() );
  QListWidgetItem *item;

  foreach( Group *group, groupList )
  {
    if( ! group->isSpecialGroup() )
    {
      item = new QListWidgetItem( group->getName(), groupList_ );

      // Set the groupId in the UserRole data
      item ->setData( Qt::UserRole, group->getId() );
      item->setFlags( Qt::ItemIsUserCheckable | Qt::ItemIsEnabled );
      item->setCheckState( Qt::Unchecked );
    }
  }

  // Force an update of the widgets (to disable the Ok button)
  interfaceChanged();
  emailAddressEdit_->setFocus();

  // Show the dialog modally
  int result = exec();

  // Set the result strings if the user has pressed the Ok button
  if( result == QDialog::Accepted )
  {
    handle   = emailAddressEdit_->text();
    groupsId = getSelectedGroups();
  }
  else
  {
    handle   = QString();
    groupsId = QStringList();
  }

  // Schedule the dialog for deletion
  deleteLater();
}



// Destructor
AddContactDialog::~AddContactDialog()
{
  KConfigGroup group = KMessConfig::instance()->getGlobalConfig( "AddContactDialog" );
  saveDialogSize( group );
}



/**
 * Controls the OK button by checking the dialog's widgets
 *
 * It's called everytime that a change is made to one of the dialog's widgets, and checks if their contents are valid.
 * Then enables or disables the OK button accordingly.
 */
void AddContactDialog::interfaceChanged()
{
  const QString& emailAddress( emailAddressEdit_->text() );

  /**
   * If you try to add a contact handle which doesn't pass basic mail validation (addresses like "" or "none"
   * or "a@bc"), the MSN Servers disconnect you and send you a so called ".NET message" with the error details.
   * This basic set of tests is more than enough to pass the server requirements.
   *
   * Other than the usual address validation (see the Account::isValidEmail() method), MSN will kick you out if
   * you try adding an address having ".co" as top level domain. So we ensure it has not. This is probably due
   * to people keeping mistyping ".com" when adding people to their list - all random 2-character domains are
   * allowed, except ".co".
   */

  // If the mail address seems correct, accept it
  if( ! emailAddress.isEmpty()
  &&  Account::isValidEmail( emailAddress )
  &&  ! emailAddress.endsWith( ".co" ) )
  {
    enableButtonOk( true );
    return;
  }

  enableButtonOk( false );
}



// Iterate to check the selected groups
const QStringList AddContactDialog::getSelectedGroups() const
{
  QStringList selectedGroups;
  QListWidgetItem *item;

  // Check for selected items
  for( int i = 0; i < groupList_->count(); i++ )
  {
    item = groupList_->item( i );
    if( item->checkState() == Qt::Checked )
    {
      // Grep the groupId
      selectedGroups.append( item->data( Qt::UserRole ).toString() );
    }
  }

  return selectedGroups;
}



#include "addcontactdialog.moc"
