/*
    kmservertest.cpp

    This file is part of KMail, the KDE mail client.
    Copyright (c) 2001-2002 Michael Haeckel <haeckel@kde.org>
    Copyright (c) 2003 Marc Mutz <mutz@kde.org>

    KMail is free software; you can redistribute it and/or modify it
    under the terms of the GNU General Public License, version 2, as
    published by the Free Software Foundation.

    KMail is distributed in the hope that it will be useful, but
    WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

    In addition, as a special exception, the copyright holders give
    permission to link the code of this program with any edition of
    the TQt library by Trolltech AS, Norway (or with modified versions
    of TQt that use the same license as TQt), and distribute linked
    combinations including the two.  You must obey the GNU General
    Public License in all respects for all of the code used other than
    TQt.  If you modify this file, you may extend this exception to
    your version of the file, but you are not obligated to do so.  If
    you do not wish to do so, delete this exception statement from
    your version.
*/

#include <config.h>

#include "kmservertest.h"

#include <tdelocale.h>
#include <tdemessagebox.h>
#include <kdebug.h>
#include <kurl.h>
#include <tdeapplication.h>
#include <tdeio/scheduler.h>
#include <tdeio/slave.h>
#include <tdeio/job.h>
#include <tdeio/global.h>

//-----------------------------------------------------------------------------
KMServerTest::KMServerTest( const TQString & protocol, const TQString & host, int port )
  : TQObject(),
    mProtocol( protocol ), mHost( host ),
    mSSL( false ), mJob( 0 ), mSlave( 0 ), mConnectionErrorCount( 0 )
{
  TDEIO::Scheduler::connect(
    TQ_SIGNAL(slaveError(TDEIO::Slave *, int, const TQString &)),
    this, TQ_SLOT(slotSlaveResult(TDEIO::Slave *, int, const TQString &)));

  if ( port == 993 || port == 995 || port == 465 )
    port = 0;

  startOffSlave( port );
}

//-----------------------------------------------------------------------------
KMServerTest::~KMServerTest()
{
  if (mJob) mJob->kill(true);
}


TDEIO::MetaData KMServerTest::slaveConfig() const {
  TDEIO::MetaData md;
  md.insert( "nologin", "on" );
  return md;
}

void KMServerTest::startOffSlave( int port ) {
  KURL url;
  url.setProtocol( mSSL ? mProtocol + 's' : mProtocol );
  url.setHost( mHost );
  if ( port )
    url.setPort( port );

  mSlave = TDEIO::Scheduler::getConnectedSlave( url, slaveConfig() );
  if ( !mSlave ) {
    slotSlaveResult( 0, 1 );
    return;
  }
  connect( mSlave, TQ_SIGNAL(metaData(const TDEIO::MetaData&)),
	   TQ_SLOT(slotMetaData(const TDEIO::MetaData&)) );

  TQByteArray packedArgs;
  TQDataStream stream( packedArgs, IO_WriteOnly );

  stream << (int) 'c';

  mJob = TDEIO::special( url, packedArgs, false );
  TDEIO::Scheduler::assignJobToSlave( mSlave, mJob );
  connect( mJob, TQ_SIGNAL(result(TDEIO::Job*)), TQ_SLOT(slotResult(TDEIO::Job*)) );
  connect( mJob, TQ_SIGNAL(infoMessage(TDEIO::Job*,const TQString&)),
	   TQ_SLOT(slotData(TDEIO::Job*,const TQString&)) );
}


//-----------------------------------------------------------------------------
void KMServerTest::slotData(TDEIO::Job *, const TQString &data)
{
  if ( mSSL )
    mListSSL = TQStringList::split(' ', data);
  else
    mListNormal = TQStringList::split(' ', data);
}


void KMServerTest::slotMetaData( const TDEIO::MetaData & md ) {
  TDEIO::MetaData::const_iterator it = md.find( "PLAIN AUTH METHODS" );
  if ( it != md.end() ) {
    mAuthNone = it.data();
    kdDebug(5006) << "mAuthNone: " << mAuthNone << endl;
  }
  it = md.find( "TLS AUTH METHODS" );
  if ( it != md.end() ) {
    mAuthTLS = it.data();
    kdDebug(5006) << "mAuthTLS: " << mAuthTLS << endl;
  }
  it = md.find( "SSL AUTH METHODS" );
  if ( it != md.end() ) {
    mAuthSSL = it.data();
    kdDebug(5006) << "mAuthSSL: " << mAuthSSL << endl;
  }
}

//-----------------------------------------------------------------------------
void KMServerTest::slotResult(TDEIO::Job *job)
{
  slotSlaveResult(mSlave, job->error());
}

//-----------------------------------------------------------------------------
void KMServerTest::slotSlaveResult(TDEIO::Slave *aSlave, int error,
  const TQString &errorText)
{
  if (aSlave != mSlave) return;
  if ( mSSL && error == 0 ) {
    // add a dummy entry to the list of SSL capabilities so that the receiver
    // of the capabilities signal can use mListSSL.isEmpty() in order to find
    // out whether SSL is supported
    mListSSL.append("SSL");
  }

  if (error != TDEIO::ERR_SLAVE_DIED && mSlave)
  {
    // disconnect slave after every connect
    TDEIO::Scheduler::disconnectSlave(mSlave);
    mSlave = 0;
  }
  if ( error == TDEIO::ERR_COULD_NOT_CONNECT )
  {
    // if one of the two connection tests fails we ignore the error
    // if both fail the host is probably not correct so we display the error
    if ( mConnectionErrorCount == 0 )
    {
      error = 0;
    }
    ++mConnectionErrorCount;
  }
  if ( error )
  {
    mJob = 0;
    KMessageBox::error( kapp->activeWindow(),
        TDEIO::buildErrorString( error, errorText ),
        i18n("Error") );
    emit capabilities( mListNormal, mListSSL );
    emit capabilities( mListNormal, mListSSL, mAuthNone, mAuthSSL, mAuthTLS );
    return;
  }
  if (!mSSL) {
    mSSL = true;
    mListNormal.append("NORMAL-CONNECTION");
    startOffSlave();
  } else {
    mJob = 0;

    emit capabilities( mListNormal, mListSSL );
    emit capabilities( mListNormal, mListSSL, mAuthNone, mAuthSSL, mAuthTLS );
  }
}


#include "kmservertest.moc"
