/*
    yahooaccount.cpp - Manages a single Yahoo account

    Copyright (c) 2003 by Gav Wood               <gav@kde.org>
    Copyright (c) 2003-2004 by Matt Rogers       <matt.rogers@kdemail.net>
    Based on code by Olivier Goffart             <ogoffart@kde.org>

    Kopete    (c) 2002-2004 by the Kopete developers  <kopete-devel@kde.org>

    *************************************************************************
    *                                                                       *
    * 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.                                   *
    *                                                                       *
    *************************************************************************
*/
//Standard Header
#include <ctime>
#include <stdlib.h>

//QT
#include <tqfont.h>
#include <tqdatetime.h>
#include <tqcolor.h>
#include <tqregexp.h>
#include <tqimage.h>
#include <tqfile.h>
#include <tqpixmap.h>
#include <tqdir.h>
#include <tqfileinfo.h>

// KDE
#include <tdelocale.h>
#include <tdeconfig.h>
#include <kdebug.h>
#include <tdeaction.h>
#include <tdepopupmenu.h>
#include <tdemessagebox.h>
#include <krun.h>
#include <kstandarddirs.h>

// Kopete
#include <kopetechatsession.h>
#include <kopetemessage.h>
#include <kopetepassword.h>
#include <kopeteuiglobal.h>
#include <knotification.h>
#include <kopetemetacontact.h>
#include <kopetecontactlist.h>
#include <kopetetransfermanager.h>
#include <kopeteview.h>
#include <contactaddednotifydialog.h>

// Yahoo
#include "yahooaccount.h"
#include "yahoocontact.h"
#include "yahooconnector.h"
#include "yahooclientstream.h"
#include "client.h"
#include "yahooverifyaccount.h"
#include "yahoowebcam.h"
#include "yahooconferencemessagemanager.h"
#include "yahooinvitelistimpl.h"
#include "yabentry.h"
#include "yahoouserinfodialog.h"

YahooAccount::YahooAccount(YahooProtocol *parent, const TQString& accountId, const char *name)
 : Kopete::PasswordedAccount(parent, accountId, 0, name)
{

	// first things first - initialise internals
	stateOnConnection = 0;
	theHaveContactList = false;
	m_protocol = parent;
	m_session = new Client( this );
	m_lastDisconnectCode = 0;
	m_currentMailCount = 0;
	m_webcam = 0;
	m_chatChatSession = 0;

	// FIXME
	//m_openInboxAction = new TDEAction( TDEIcon("mail-folder-inbox"), i18n( "Open Inbo&x..." ), this );
        //, "m_openInboxAction" );
	//TQObject::connect(m_openInboxAction, TQT_SIGNAL( triggered(bool) ), this, TQT_SLOT( slotOpenInbox() ) );
	//m_openYABAction = new TDEAction( TDEIcon("x-office-address-book"), i18n( "Open &Address book..." ), this );
        //, "m_openYABAction" );
	//TQObject::connect(m_openYABAction, TQT_SIGNAL( triggered(bool) ), this, TQT_SLOT( slotOpenYAB() ) );
	//m_editOwnYABEntry = new TDEAction( TDEIcon("document-properties"), i18n( "&Edit my contact details..."), this );
        //, "m_editOwnYABEntry" );
	//TQObject::connect(m_editOwnYABEntry, TQT_SIGNAL( triggered(bool) ), this, TQT_SLOT( slotEditOwnYABEntry() ) );
	//m_joinChatAction = new TDEAction( TDEIcon("im-chat-room-join"), i18n( "&Join chat room..."), this );
        //, "m_joinChatAction" );
	//TQObject::connect(m_joinChatAction, TQT_SIGNAL( triggered(bool) ), this, TQT_SLOT( slotJoinChatRoom() ) );

	m_openInboxAction = new TDEAction( i18n( "Open Inbo&x..." ), "mail_generic", 0, this, TQT_SLOT( slotOpenInbox() ), this, "m_openInboxAction" );
	m_openYABAction = new TDEAction( i18n( "Open &Addressbook..." ), "contents", 0, this, TQT_SLOT( slotOpenYAB() ), this, "m_openYABAction" );
	m_editOwnYABEntry = new TDEAction( i18n( "&Edit my contact details..."), "contents", 0, this, TQT_SLOT( slotEditOwnYABEntry() ), this, "m_editOwnYABEntry" );
	m_joinChatAction = new TDEAction( i18n( "&Join chat room..."), "contents", 0, this, TQT_SLOT( slotJoinChatRoom() ), this, "m_joinChatAction");

	YahooContact* _myself=new YahooContact( this, accountId.lower(), accountId, Kopete::ContactList::self()->myself() );
	setMyself( _myself );
	_myself->setOnlineStatus( parent->Offline );
	myself()->setProperty( YahooProtocol::protocol()->iconRemoteUrl, configGroup()->readEntry( "iconRemoteUrl", "" ) );
	myself()->setProperty( Kopete::Global::Properties::self()->photo(), configGroup()->readEntry( "iconLocalUrl", "" ) );
	myself()->setProperty( YahooProtocol::protocol()->iconCheckSum, configGroup()->readEntry( "iconCheckSum", 0 ) );
	myself()->setProperty( YahooProtocol::protocol()->iconExpire, configGroup()->readEntry( "iconExpire", 0 ) );

// 	initConnectionSignals( MakeConnections );

	TQString displayName = configGroup()->readEntry(TQString::fromLatin1("displayName"), TQString());
	if(!displayName.isEmpty())
		_myself->setNickName(displayName);

	m_YABLastMerge = configGroup()->readNumEntry( "YABLastMerge", 0 );
	m_YABLastRemoteRevision = configGroup()->readNumEntry( "YABLastRemoteRevision", 0 );

	m_session->setUserId( accountId.lower() );
	m_session->setPictureChecksum( myself()->property( YahooProtocol::protocol()->iconCheckSum ).value().toInt() );

	setupActions( false );
}

YahooAccount::~YahooAccount()
{
	if( m_webcam )
		m_webcam->stopTransmission();
}

void YahooAccount::setServer( const TQString &server )
{
	configGroup()->writeEntry( TQString::fromLatin1( "Server" ), server );
}

void YahooAccount::setPort( int port )
{
	configGroup()->writeEntry( TQString::fromLatin1( "Port" ), port );
}

void YahooAccount::slotGoStatus( int status, const TQString &awayMessage)
{
	kdDebug(YAHOO_GEN_DEBUG) << "GoStatus: " << status << " msg: " << awayMessage << endl;
	if( !isConnected() )
	{
		connect( m_protocol->statusFromYahoo( status ) );
		stateOnConnection = status;
	}
	else
	{
		m_session->changeStatus( Yahoo::Status( status ), awayMessage,
			(status == Yahoo::StatusAvailable)? Yahoo::StatusTypeAvailable : Yahoo::StatusTypeAway );

		//sets the awayMessage property for the owner of the account. shows up in the statusbar icon's tooltip. the property is unset when awayMessage is null
		myself()->setProperty( m_protocol->awayMessage, awayMessage );
		myself()->setOnlineStatus( m_protocol->statusFromYahoo( status ) );
	}
}

Client *YahooAccount::yahooSession()
{
	return m_session ? m_session : 0L;
}

TQString YahooAccount::stripMsgColorCodes(const TQString& msg)
{
	TQString filteredMsg = msg;

	//Handle bold, underline and italic messages
	filteredMsg.replace( "\033[1m", "<b>" );
	filteredMsg.replace( "\033[x1m", "</b>" );
	filteredMsg.replace( "\033[2m", "<i>" );
	filteredMsg.replace( "\033[x2m", "</i>" );
	filteredMsg.replace( "\033[4m", "<u>" );
	filteredMsg.replace( "\033[x4m", "</u>" );

	//PIDGIN doesn't check for ^[[3m. Does this ever get sent?
	filteredMsg.replace( "\033[3m", "<i>" );
	filteredMsg.replace( "\033[x3m", "</i>" );

	//Strip link tags
	filteredMsg.remove( "\033[lm" );
	filteredMsg.remove( "\033[xlm" );

	//Remove color codes and other residual formatting
	filteredMsg.remove( TQRegExp("\033\\[[^m]*m") );

	return filteredMsg;
}

TQColor YahooAccount::getMsgColor(const TQString& msg)
{
	/* Yahoo sends a message either with color or without color
	 * so we have to use this really hacky method to get colors
	 */
	//kdDebug(YAHOO_GEN_DEBUG) << "msg is " << msg;
	//Please note that some of the colors are hard-coded to
	//match the yahoo colors
	if ( msg.find("\033[38m") != -1 )
		return TQt::red;
	if ( msg.find("\033[34m") != -1 )
		return TQt::green;
	if ( msg.find("\033[31m") != -1 )
		return TQt::blue;
	if ( msg.find("\033[39m") != -1 )
		return TQt::yellow;
	if ( msg.find("\033[36m") != -1 )
		return TQt::darkMagenta;
	if ( msg.find("\033[32m") != -1 )
		return TQt::cyan;
	if ( msg.find("\033[37m") != -1 )
		return TQColor("#FFAA39");
	if ( msg.find("\033[35m") != -1 )
		return TQColor("#FFD8D8");
	if ( msg.find("\033[#") != -1 )
	{
		kdDebug(YAHOO_GEN_DEBUG) << "Custom color is " << msg.mid(msg.find("\033[#")+2,7) << endl;
		return TQColor(msg.mid(msg.find("\033[#")+2,7));
	}

	//return a default value just in case
	return TQt::black;
}

void YahooAccount::initConnectionSignals( enum SignalConnectionType sct )
{
	if ( !m_session )
		return;

	if ( sct == MakeConnections )
	{
		TQObject::connect(m_session, TQT_SIGNAL(loggedIn( int, const TQString &)),
		                 this, TQT_SLOT(slotLoginResponse(int, const TQString &)) );

		TQObject::connect(m_session, TQT_SIGNAL(disconnected()),
		                 this, TQT_SLOT(slotDisconnected()) );

		TQObject::connect(m_session, TQT_SIGNAL(loginFailed()),
		                 this, TQT_SLOT(slotLoginFailed()) );

		TQObject::connect(m_session, TQT_SIGNAL(error(int)),
		                 this, TQT_SLOT(slotError(int)));

		TQObject::connect(m_session, TQT_SIGNAL(gotBuddy(const TQString &, const TQString &, const TQString &)),
		                 this, TQT_SLOT(slotGotBuddy(const TQString &, const TQString &, const TQString &)));

		TQObject::connect(m_session, TQT_SIGNAL(buddyAddResult(const TQString &, const TQString &, bool)),
				 this, TQT_SLOT(slotBuddyAddResult(const TQString &, const TQString &, bool)));

		TQObject::connect(m_session, TQT_SIGNAL(buddyRemoveResult(const TQString &, const TQString &, bool)),
				 this, TQT_SLOT(slotBuddyRemoveResult(const TQString &, const TQString &, bool)));

		TQObject::connect(m_session, TQT_SIGNAL(buddyChangeGroupResult(const TQString &, const TQString &, bool)),
				 this, TQT_SLOT(slotBuddyChangeGroupResult(const TQString &, const TQString &, bool)));

		TQObject::connect(m_session, TQT_SIGNAL(authorizationAccepted( const TQString & )),
		                 this, TQT_SLOT(slotAuthorizationAccepted( const TQString & )) );

		TQObject::connect(m_session, TQT_SIGNAL(authorizationRejected( const TQString &, const TQString & )),
		                 this, TQT_SLOT(slotAuthorizationRejected( const TQString &, const TQString & )) );

		TQObject::connect(m_session, TQT_SIGNAL(gotAuthorizationRequest( const TQString &, const TQString &, const TQString & )),
		                 this, TQT_SLOT(slotgotAuthorizationRequest( const TQString &, const TQString &, const TQString & )) );

		TQObject::connect(m_session, TQT_SIGNAL(statusChanged(const TQString&,int,const TQString&,int,int,int)),
		                 this, TQT_SLOT(slotStatusChanged(const TQString&,int,const TQString&,int,int,int)));

		TQObject::connect(m_session, TQT_SIGNAL(stealthStatusChanged(const TQString &, Yahoo::StealthStatus)),
		                 this, TQT_SLOT(slotStealthStatusChanged( const TQString &, Yahoo::StealthStatus)) );

		TQObject::connect(m_session, TQT_SIGNAL(gotIm(const TQString&, const TQString&, long, int)),
		                 this, TQT_SLOT(slotGotIm(const TQString &, const TQString&, long, int)));

		TQObject::connect(m_session, TQT_SIGNAL(gotBuzz(const TQString&, long)),
		                 this, TQT_SLOT(slotGotBuzz(const TQString &, long)));

		TQObject::connect(m_session, TQT_SIGNAL( gotConferenceInvite( const TQString&, const TQString&,
		                                                   const TQString&, const TQStringList&) ),
		                 this,
		                 TQT_SLOT( slotGotConfInvite( const TQString&, const TQString&,
		                                          const TQString&, const TQStringList& ) ) );

		TQObject::connect(m_session, TQT_SIGNAL(confUserDeclined(const TQString&, const TQString &, const TQString &)),
		                 this,
		                 TQT_SLOT(slotConfUserDecline( const TQString &, const TQString &, const TQString &)) );

		TQObject::connect(m_session , TQT_SIGNAL(confUserJoined( const TQString &, const TQString &)), this,
		                 TQT_SLOT(slotConfUserJoin( const TQString &, const TQString &)) );

		TQObject::connect(m_session , TQT_SIGNAL(confUserLeft( const TQString &, const TQString &)), this,
		                 TQT_SLOT(slotConfUserLeave( const TQString &, const TQString &)) );

		TQObject::connect(m_session , TQT_SIGNAL(gotConferenceMessage( const TQString &, const TQString &, const TQString &)), this,
		                 TQT_SLOT(slotConfMessage( const TQString &, const TQString &, const TQString &)) );

		TQObject::connect(m_session,
		                 TQT_SIGNAL(incomingFileTransfer(const TQString &, const TQString &, long, const TQString &, const TQString &, unsigned long, const TQPixmap &)),
		                 this,
		                 TQT_SLOT(slotGotFile(const TQString&, const TQString&, long, const TQString&, const TQString&, unsigned long, const TQPixmap &)));

		TQObject::connect(m_session, TQT_SIGNAL(fileTransferComplete(unsigned int)), this,
		                 TQT_SLOT(slotFileTransferComplete(unsigned int)) );

		TQObject::connect(m_session, TQT_SIGNAL(fileTransferBytesProcessed(unsigned int,unsigned int)), this,
		                 TQT_SLOT(slotFileTransferBytesProcessed(unsigned int,unsigned int)) );

		TQObject::connect(m_session, TQT_SIGNAL(fileTransferError(unsigned int,int,const TQString &)), this,
		                 TQT_SLOT(slotFileTransferError(unsigned int,int,const TQString &)) );

		TQObject::connect(m_session, TQT_SIGNAL(typingNotify(const TQString &, int)), this ,
		                 TQT_SLOT(slotTypingNotify(const TQString &, int)));

// 		TQObject::connect(m_session, TQT_SIGNAL(gameNotify(const TQString &, int)), this,
// 		                 TQT_SLOT(slotGameNotify( const TQString &, int)));

		TQObject::connect(m_session, TQT_SIGNAL(mailNotify(const TQString&, const TQString&, int)), this,
		                 TQT_SLOT(slotMailNotify(const TQString &, const TQString&, int)));

		TQObject::connect(m_session, TQT_SIGNAL(systemMessage(const TQString&)), this,
		                 TQT_SLOT(slotSystemMessage(const TQString &)));

// 		TQObject::connect(m_session, TQT_SIGNAL(gotIdentities(const TQStringList &)), this,
// 		                 TQT_SLOT(slotGotIdentities( const TQStringList&)));

		TQObject::connect(m_session, TQT_SIGNAL(gotWebcamInvite(const TQString&)), this, TQT_SLOT(slotGotWebcamInvite(const TQString&)));

		TQObject::connect(m_session, TQT_SIGNAL(webcamNotAvailable(const TQString&)), this, TQT_SLOT(slotWebcamNotAvailable(const TQString&)));

		TQObject::connect(m_session, TQT_SIGNAL(webcamImageReceived(const TQString&, const TQPixmap& )), this, TQT_SLOT(slotGotWebcamImage(const TQString&, const TQPixmap& )));

		TQObject::connect(m_session, TQT_SIGNAL(webcamClosed(const TQString&, int )), this, TQT_SLOT(slotWebcamClosed(const TQString&, int )));

		TQObject::connect(m_session, TQT_SIGNAL(webcamPaused(const TQString&)), this, TQT_SLOT(slotWebcamPaused(const TQString&)));

		TQObject::connect(m_session, TQT_SIGNAL(webcamReadyForTransmission()), this, TQT_SLOT(slotWebcamReadyForTransmission()));

		TQObject::connect(m_session, TQT_SIGNAL(webcamStopTransmission()), this, TQT_SLOT(slotWebcamStopTransmission()));

		TQObject::connect(m_session, TQT_SIGNAL(webcamViewerJoined(const TQString&)), this, TQT_SLOT(slotWebcamViewerJoined(const TQString&)));

		TQObject::connect(m_session, TQT_SIGNAL(webcamViewerLeft(const TQString&)), this, TQT_SLOT(slotWebcamViewerLeft(const TQString&)));

		TQObject::connect(m_session, TQT_SIGNAL(webcamViewerRequest(const TQString&)), this, TQT_SLOT(slotWebcamViewerRequest( const TQString&)));

		TQObject::connect(m_session, TQT_SIGNAL(pictureStatusNotify( const TQString&, int )), TQT_SLOT(slotPictureStatusNotify( const TQString&, int)));

		TQObject::connect(m_session, TQT_SIGNAL(pictureDownloaded(const TQString&, const TQByteArray &, int)), this, TQT_SLOT(slotGotBuddyIcon(const TQString&, const TQByteArray &, int)) );

		TQObject::connect(m_session, TQT_SIGNAL(pictureInfoNotify(const TQString&, KURL, int)), this, TQT_SLOT(slotGotBuddyIconInfo(const TQString&, KURL, int )));

		TQObject::connect(m_session, TQT_SIGNAL(pictureChecksumNotify(const TQString&, int)), this, TQT_SLOT(slotGotBuddyIconChecksum(const TQString&, int )));

		TQObject::connect(m_session, TQT_SIGNAL(pictureRequest(const TQString&)), this, TQT_SLOT(slotGotBuddyIconRequest(const TQString&)) );

		TQObject::connect(m_session, TQT_SIGNAL(pictureUploaded( const TQString &, int)), this, TQT_SLOT(slotBuddyIconChanged(const TQString&, int)));

		TQObject::connect(m_session, TQT_SIGNAL(gotYABEntry( YABEntry * )), this, TQT_SLOT(slotGotYABEntry( YABEntry * )));

		TQObject::connect(m_session, TQT_SIGNAL(modifyYABEntryError( YABEntry *, const TQString & )), this, TQT_SLOT(slotModifyYABEntryError( YABEntry *, const TQString & )));

		TQObject::connect(m_session, TQT_SIGNAL(gotYABRevision( long, bool )), this, TQT_SLOT(slotGotYABRevision( long , bool )) );

		TQObject::connect(m_session, TQT_SIGNAL(chatRoomJoined(int,int,TQString,TQString)), this, TQT_SLOT(slotChatJoined(int,int,TQString,TQString)));

		TQObject::connect(m_session, TQT_SIGNAL(chatBuddyHasJoined(TQString,TQString,bool)), this, TQT_SLOT(slotChatBuddyHasJoined(TQString,TQString,bool)));

		TQObject::connect(m_session, TQT_SIGNAL(chatBuddyHasLeft(TQString,TQString)), this, TQT_SLOT(slotChatBuddyHasLeft(TQString,TQString)));

		TQObject::connect(m_session, TQT_SIGNAL(chatMessageReceived(TQString,TQString,TQString)), this, TQT_SLOT(slotChatMessageReceived(TQString,TQString,TQString)));
	}

	if ( sct == DeleteConnections )
	{
		TQObject::disconnect(m_session, TQT_SIGNAL(loggedIn(int, const TQString &)),
		                    this, TQT_SLOT(slotLoginResponse(int, const TQString &)) );

		TQObject::disconnect(m_session, TQT_SIGNAL(disconnected()),
		                    this, TQT_SLOT(slotDisconnected()) );

		TQObject::disconnect(m_session, TQT_SIGNAL(loginFailed()),
		                    this, TQT_SLOT(slotLoginFailed()) );

		TQObject::disconnect(m_session, TQT_SIGNAL(error(int)),
		                 this, TQT_SLOT(slotError(int)));

		TQObject::disconnect(m_session, TQT_SIGNAL(gotBuddy(const TQString &, const TQString &, const TQString &)),
		                    this, TQT_SLOT(slotGotBuddy(const TQString &, const TQString &, const TQString &)));

		TQObject::disconnect(m_session, TQT_SIGNAL(buddyAddResult(const TQString &, const TQString &, bool)),
		                    this, TQT_SLOT(slotBuddyAddResult(const TQString &, const TQString &, bool)));

		TQObject::disconnect(m_session, TQT_SIGNAL(buddyRemoveResult(const TQString &, const TQString &, bool)),
		                    this, TQT_SLOT(slotBuddyRemoveResult(const TQString &, const TQString &, bool)));

		TQObject::disconnect(m_session, TQT_SIGNAL(buddyChangeGroupResult(const TQString &, const TQString &, bool)),
				 this, TQT_SLOT(slotBuddyChangeGroupResult(const TQString &, const TQString &, bool)));

		TQObject::disconnect(m_session, TQT_SIGNAL(authorizationAccepted( const TQString &)),
		                 this, TQT_SLOT(slotAuthorizationAccepted( const TQString &)) );

		TQObject::disconnect(m_session, TQT_SIGNAL(authorizationRejected( const TQString &, const TQString &)),
		                    this, TQT_SLOT(slotAuthorizationRejected( const TQString &, const TQString & )) );

		TQObject::disconnect(m_session, TQT_SIGNAL(gotAuthorizationRequest( const TQString &, const TQString &, const TQString & )),
		                 this, TQT_SLOT(slotgotAuthorizationRequest( const TQString &, const TQString &, const TQString & )) );

		TQObject::disconnect(m_session, TQT_SIGNAL(statusChanged(const TQString&,int,const TQString&,int,int,int)),
		                    this, TQT_SLOT(slotStatusChanged(const TQString&,int,const TQString&,int,int,int)));

		TQObject::disconnect(m_session, TQT_SIGNAL(stealthStatusChanged(const TQString &, Yahoo::StealthStatus)),
		                 this, TQT_SLOT(slotStealthStatusChanged( const TQString &, Yahoo::StealthStatus)) );

		TQObject::disconnect(m_session, TQT_SIGNAL(gotIm(const TQString&, const TQString&, long, int)),
		                    this, TQT_SLOT(slotGotIm(const TQString &, const TQString&, long, int)));

		TQObject::disconnect(m_session, TQT_SIGNAL(gotBuzz(const TQString&, long)),
		                    this, TQT_SLOT(slotGotBuzz(const TQString &, long)));

		TQObject::disconnect(m_session,
		                    TQT_SIGNAL( gotConferenceInvite( const TQString&, const TQString&,
		                                           const TQString&, const TQStringList&) ),
		                    this,
		                    TQT_SLOT( slotGotConfInvite( const TQString&, const TQString&,
		                                             const TQString&, const TQStringList&) ) );

		TQObject::disconnect(m_session,
		                    TQT_SIGNAL(confUserDeclined(const TQString&, const TQString &, const TQString &)),
		                    this,
		                    TQT_SLOT(slotConfUserDecline( const TQString &, const TQString &, const TQString& ) ) );

		TQObject::disconnect(m_session , TQT_SIGNAL(confUserJoined( const TQString &, const TQString &)),
		                    this, TQT_SLOT(slotConfUserJoin( const TQString &, const TQString &)) );

		TQObject::disconnect(m_session , TQT_SIGNAL(confUserLeft( const TQString &, const TQString &)),
		                    this, TQT_SLOT(slotConfUserLeave( const TQString &, const TQString &)) );

		TQObject::disconnect(m_session , TQT_SIGNAL(gotConferenceMessage( const TQString &, const TQString &, const TQString &)), this,
		                    TQT_SLOT(slotConfMessage( const TQString &, const TQString &, const TQString &)) );

		TQObject::disconnect(m_session,
		                    TQT_SIGNAL(incomingFileTransfer(const TQString &, const TQString &,
			                    long, const TQString &, const TQString &, unsigned long, const TQPixmap &)),
		                    this,
		                    TQT_SLOT(slotGotFile(const TQString&, const TQString&,
		                                     long, const TQString&, const TQString&, unsigned long, const TQPixmap &)));

		TQObject::disconnect(m_session, TQT_SIGNAL(fileTransferComplete(unsigned int)), this,
		                 TQT_SLOT(slotFileTransferComplete(unsigned int)) );

		TQObject::disconnect(m_session, TQT_SIGNAL(fileTransferBytesProcessed(unsigned int,unsigned int)), this,
		                 TQT_SLOT(slotFileTransferBytesProcessed(unsigned int,unsigned int)) );

		TQObject::disconnect(m_session, TQT_SIGNAL(fileTransferError(unsigned int,int,const TQString &)), this,
		                 TQT_SLOT(slotFileTransferError(unsigned int,int,const TQString &)) );

		TQObject::disconnect(m_session, TQT_SIGNAL(typingNotify(const TQString &, int)), this ,
		                    TQT_SLOT(slotTypingNotify(const TQString &, int)));

// 		TQObject::disconnect(m_session, TQT_SIGNAL(gameNotify(const TQString &, int)), this,
// 		                    TQT_SLOT(slotGameNotify( const TQString &, int)));

		TQObject::disconnect(m_session, TQT_SIGNAL(mailNotify(const TQString&, const TQString&, int)), this,
		                    TQT_SLOT(slotMailNotify(const TQString &, const TQString&, int)));

		TQObject::disconnect(m_session, TQT_SIGNAL(systemMessage(const TQString&)), this,
		                    TQT_SLOT(slotSystemMessage(const TQString &)));

// 		TQObject::disconnect(m_session, TQT_SIGNAL(gotIdentities(const TQStringList &)), this,
// 		                    TQT_SLOT(slotGotIdentities( const TQStringList&)));

		TQObject::disconnect(m_session, TQT_SIGNAL(gotWebcamInvite(const TQString&)), this, TQT_SLOT(slotGotWebcamInvite(const TQString&)));

		TQObject::disconnect(m_session, TQT_SIGNAL(webcamNotAvailable(const TQString&)), this, TQT_SLOT(slotWebcamNotAvailable(const TQString&)));

		TQObject::disconnect(m_session, TQT_SIGNAL(webcamImageReceived(const TQString&, const TQPixmap& )), this, TQT_SLOT(slotGotWebcamImage(const TQString&, const TQPixmap& )));

		TQObject::disconnect(m_session, TQT_SIGNAL(webcamClosed(const TQString&, int )), this, TQT_SLOT(slotWebcamClosed(const TQString&, int )));

		TQObject::disconnect(m_session, TQT_SIGNAL(webcamPaused(const TQString&)), this, TQT_SLOT(slotWebcamPaused(const TQString&)));

		TQObject::disconnect(m_session, TQT_SIGNAL(webcamReadyForTransmission()), this, TQT_SLOT(slotWebcamReadyForTransmission()));

		TQObject::disconnect(m_session, TQT_SIGNAL(webcamStopTransmission()), this, TQT_SLOT(slotWebcamStopTransmission()));

		TQObject::disconnect(m_session, TQT_SIGNAL(webcamViewerJoined(const TQString&)), this, TQT_SLOT(slotWebcamViewerJoined(const TQString&)));

		TQObject::disconnect(m_session, TQT_SIGNAL(webcamViewerLeft(const TQString&)), this, TQT_SLOT(slotWebcamViewerLeft(const TQString&)));

		TQObject::disconnect(m_session, TQT_SIGNAL(webcamViewerRequest(const TQString&)), this, TQT_SLOT(slotWebcamViewerRequest( const TQString&)));

		TQObject::disconnect(m_session, TQT_SIGNAL(pictureDownloaded(const TQString&, const TQByteArray &, int )), this, TQT_SLOT(slotGotBuddyIcon(const TQString&, const TQByteArray &,int )));

		TQObject::disconnect(m_session, TQT_SIGNAL(pictureInfoNotify(const TQString&, KURL, int)), this, TQT_SLOT(slotGotBuddyIconInfo(const TQString&, KURL, int )));

		TQObject::disconnect(m_session, TQT_SIGNAL(pictureRequest(const TQString&)), this, TQT_SLOT(slotGotBuddyIconRequest(const TQString&)) );

		TQObject::disconnect(m_session, TQT_SIGNAL(pictureUploaded( const TQString &, int )), this, TQT_SLOT(slotBuddyIconChanged(const TQString&, int)));

		TQObject::disconnect(m_session, TQT_SIGNAL(pictureStatusNotify( const TQString&, int )), this, TQT_SLOT(slotPictureStatusNotify( const TQString&, int)));

		TQObject::disconnect(m_session, TQT_SIGNAL(pictureChecksumNotify(const TQString&, int)), this, TQT_SLOT(slotGotBuddyIconChecksum(const TQString&, int )));

		TQObject::disconnect(m_session, TQT_SIGNAL(gotYABEntry( YABEntry * )), this, TQT_SLOT(slotGotYABEntry( YABEntry * )));

		TQObject::disconnect(m_session, TQT_SIGNAL(modifyYABEntryError( YABEntry *, const TQString & )), this, TQT_SLOT(slotModifyYABEntryError( YABEntry *, const TQString & )));

		TQObject::disconnect(m_session, TQT_SIGNAL(gotYABRevision( long, bool )), this, TQT_SLOT(slotGotYABRevision( long , bool )) );

		TQObject::disconnect(m_session, TQT_SIGNAL(chatRoomJoined(int,int,const TQString&,const TQString&)), this, TQT_SLOT(slotChatJoined(int,int,const TQString&,const TQString&)));

		TQObject::disconnect(m_session, TQT_SIGNAL(chatBuddyHasJoined(const TQString&,const TQString&,bool)), this, TQT_SLOT(slotChatBuddyHasJoined(const TQString&,const TQString&,bool)));

		TQObject::disconnect(m_session, TQT_SIGNAL(chatBuddyHasLeft(const TQString&,const TQString&)), this, TQT_SLOT(slotChatBuddyHasLeft(const TQString&,const TQString&)));

		TQObject::disconnect(m_session, TQT_SIGNAL(chatMessageReceived(const TQString&,const TQString&,const TQString&)), this, TQT_SLOT(slotChatMessageReceived(const TQString&,const TQString&,const TQString&)));
	}
}

void YahooAccount::connectWithPassword( const TQString &passwd )
{
	kdDebug(YAHOO_GEN_DEBUG) ;
	if ( isAway() )
	{
		slotGoOnline();
		return;
	}

	if ( isConnected() ||
	     myself()->onlineStatus() == m_protocol->Connecting )
	{
		kdDebug(YAHOO_GEN_DEBUG) << "Yahoo plugin: Ignoring connect request (already connected)." << endl;
		return;

	}

	if ( passwd.isNull() )
	{ //cancel the connection attempt
		static_cast<YahooContact*>( myself() )->setOnlineStatus( m_protocol->Offline );
		return;
	}

	TQString server = configGroup()->readEntry( "Server", "scsa.msg.yahoo.com" );
	int port = configGroup()->readNumEntry( "Port", 5050 );

	initConnectionSignals( MakeConnections );

	//YahooSessionManager::manager()->setPager( server, port );
	//m_session = YahooSessionManager::manager()->createSession( accountId(), passwd );
	kdDebug(YAHOO_GEN_DEBUG) << "Attempting to connect to Yahoo on <" << server << ":"
		<< port << ">. user <" << accountId() << ">"  << endl;
	static_cast<YahooContact *>( myself() )->setOnlineStatus( m_protocol->Connecting );
	m_session->setStatusOnConnect( Yahoo::Status( initialStatus().internalStatus() ) );
	m_session->connect( server, port, accountId().lower(), passwd );
}

void YahooAccount::disconnect()
{
	kdDebug(YAHOO_GEN_DEBUG) << k_funcinfo << endl;

	m_currentMailCount = 0;
	if ( isConnected() )
	{
		kdDebug(YAHOO_GEN_DEBUG) <<  "Attempting to disconnect from Yahoo server " << endl;

		disconnected( Manual );
		m_session->close();
		static_cast<YahooContact *>( myself() )->setOnlineStatus( m_protocol->Offline );

		// FIXME: to check
		//TQHash<TQString,Kopete::Contact*>::ConstIterator it, itEnd = contacts().constEnd();
		//for ( it = contacts().constBegin(); it != itEnd; ++it )
		//	static_cast<YahooContact *>( it.value() )->setOnlineStatus( m_protocol->Offline );
		for ( TQDictIterator<Kopete::Contact> i( contacts() ); i.current(); ++i )
			static_cast<YahooContact *>( i.current() )->setOnlineStatus( m_protocol->Offline );

		static_cast<YahooContact*>( myself() )->setOnlineStatus( m_protocol->Offline );
	}
	else
	{       //make sure we set everybody else offline explicitly, just for cleanup
		kdDebug(YAHOO_GEN_DEBUG) << "Cancelling active login attempts (not fully connected)." << endl;
		m_session->cancelConnect();

		// FIXME: to check
		//TQHash<TQString,Kopete::Contact*>::ConstIterator it, itEnd = contacts().constEnd();
		//for ( it = contacts().constBegin(); it != itEnd; ++it )
		//	static_cast<YahooContact*>( it.value() )->setOnlineStatus( m_protocol->Offline );
		for ( TQDictIterator<Kopete::Contact> i(contacts()); i.current(); ++i )
			static_cast<YahooContact*>( i.current() )->setOnlineStatus( m_protocol->Offline );

		static_cast<YahooContact*>( myself() )->setOnlineStatus( m_protocol->Offline );
	}

	initConnectionSignals( DeleteConnections );
	setupActions( false );
	theHaveContactList = false;
}

void YahooAccount::verifyAccount( const TQString &word )
{
	kdDebug(YAHOO_GEN_DEBUG) << "Word: s" << word << endl;
	m_session->setVerificationWord( word );
	disconnected( BadPassword );
}

void YahooAccount::setAway(bool status, const TQString &awayMessage)
{
	kdDebug(YAHOO_GEN_DEBUG) ;

	if( awayMessage.isEmpty() )
		slotGoStatus( status ? 2 : 0 );
	else
		slotGoStatus( status ? 99 : 0, awayMessage );
}

void YahooAccount::slotConnected()
{
	kdDebug(YAHOO_GEN_DEBUG) << "Moved to slotLoginResponse for the moment" << endl;
}

void YahooAccount::slotGoOnline()
{
	kdDebug(YAHOO_GEN_DEBUG) ;
	if( !isConnected() )
		connect( m_protocol->Online );
	else
		slotGoStatus(0);
}

void YahooAccount::slotGoOffline()
{
	if ( isConnected() )
		disconnect();
	else
		static_cast<YahooContact *>( myself() )->setOnlineStatus( m_protocol->Offline );
}

TDEActionMenu* YahooAccount::actionMenu()
{
	kdDebug(YAHOO_GEN_DEBUG) << k_funcinfo << endl;

	// FIXME (to check)
	//Kopete::Account::fillActionMenu( actionMenu );
	TDEActionMenu *theActionMenu = Kopete::Account::actionMenu();

	// FIXME: (to check)
	//actionMenu->addSeparator();
	//actionMenu->addAction( m_openInboxAction );
	//actionMenu->addAction( m_openYABAction );
	//actionMenu->addAction( m_editOwnYABEntry );
	//actionMenu->addAction( m_joinChatAction );

	theActionMenu->popupMenu()->insertSeparator();
	theActionMenu->insert( m_editOwnYABEntry );
	theActionMenu->insert( m_openInboxAction );
	theActionMenu->insert( m_openYABAction );
	theActionMenu->insert( m_joinChatAction );

	return theActionMenu;
}

YahooContact *YahooAccount::contact( const TQString &id )
{
	return static_cast<YahooContact *>(contacts()[id]);
}

bool YahooAccount::createContact(const TQString &contactId, Kopete::MetaContact *parentContact )
{
//	kdDebug(YAHOO_GEN_DEBUG) << " contactId: " << contactId;

	if(!contact(contactId))
	{
		// FIXME: New Contacts are NOT added to KABC, because:
		// How on earth do you tell if a contact is being deserialised or added brand new here?
			// -- actualy (oct 2004) this method is only called when new contact are added.  but this will
			//    maybe change and you will be noticed   --Olivier
		YahooContact *newContact = new YahooContact( this, contactId,
		                                             parentContact->displayName(), parentContact );
		return newContact != 0;
	}
	else
		kdDebug(YAHOO_GEN_DEBUG) << "Contact already exists" << endl;

	return false;
}

bool YahooAccount::createChatContact(const TQString &nick)
{
	Kopete::MetaContact *m = new Kopete::MetaContact;
	m->setTemporary( true );
	return createContact( nick, m );
}

void YahooAccount::sendFile( YahooContact *to, const KURL &url )
{
	TQFile file( url.path() );

	Kopete::Transfer *transfer = Kopete::TransferManager::transferManager()->addTransfer ( to,
		url.fileName(), file.size(), to->userId(), Kopete::FileTransferInfo::Outgoing );
	m_session->sendFile( transfer->info().transferId(), to->userId(), TQString(), url );

	TQObject::connect( transfer, TQT_SIGNAL(result( TDEIO::Job * )), this, TQT_SLOT(slotFileTransferResult( TDEIO::Job * )) );

	m_fileTransfers.insert( transfer->info().transferId(), transfer );
}

void YahooAccount::setupActions( bool connected )
{
	m_joinChatAction->setEnabled( connected );
	m_editOwnYABEntry->setEnabled( connected );
}

/***************************************************************************
 *                                                                         *
 *   Slot for KYahoo signals                                               *
 *                                                                         *
 ***************************************************************************/

void YahooAccount::slotLoginResponse( int succ , const TQString &url )
{
	kdDebug(YAHOO_GEN_DEBUG) << succ << ", " << url << ")]" << endl;
	TQString errorMsg;
	setupActions( succ == Yahoo::LoginOk );
	if ( succ == Yahoo::LoginOk || (succ == Yahoo::LoginDupl && m_lastDisconnectCode == 2) )
	{
		if ( initialStatus().internalStatus() )
		{
			static_cast<YahooContact *>( myself() )->setOnlineStatus( initialStatus() );
		}
		else
		{
			static_cast<YahooContact *>( myself() )->setOnlineStatus( m_protocol->Online );
		}


		setBuddyIcon( myself()->property( Kopete::Global::Properties::self()->photo() ).value().toString() );
		m_session->getYABEntries( m_YABLastMerge, m_YABLastRemoteRevision );
		IDs.clear();
		m_lastDisconnectCode = 0;
		theHaveContactList = true;
		return;
	}
	else if(succ == Yahoo::LoginPasswd)
	{
		initConnectionSignals( DeleteConnections );
		password().setWrong();
		static_cast<YahooContact *>( myself() )->setOnlineStatus( m_protocol->Offline );
		disconnected( BadPassword );
		return;
	}
	else if(succ == Yahoo::LoginLock)
	{
		initConnectionSignals( DeleteConnections );
		errorMsg = i18n("Could not log into the Yahoo service: your account has been locked.\nVisit %1 to reactivate it.").arg(url);
		KMessageBox::queuedMessageBox(Kopete::UI::Global::mainWidget(), KMessageBox::Error, errorMsg);
		static_cast<YahooContact *>( myself() )->setOnlineStatus( m_protocol->Offline );
		disconnected( BadUserName ); // FIXME: add a more appropriate disconnect reason
		return;
	}
	else if( succ == Yahoo::LoginUname )
	{
		initConnectionSignals( DeleteConnections );
		errorMsg = i18n("Could not log into the Yahoo service: the username specified was invalid.");
		KMessageBox::queuedMessageBox(Kopete::UI::Global::mainWidget(), KMessageBox::Error, errorMsg);
		static_cast<YahooContact *>( myself() )->setOnlineStatus( m_protocol->Offline );
		disconnected( BadUserName );
		return;
	}
	else if( succ == Yahoo::LoginDupl && m_lastDisconnectCode != 2 )
	{
		initConnectionSignals( DeleteConnections );
		errorMsg = i18n("You have been logged out of the Yahoo service, possibly due to a duplicate login.");
		KMessageBox::queuedMessageBox(Kopete::UI::Global::mainWidget(), KMessageBox::Error, errorMsg);
		static_cast<YahooContact *>( myself() )->setOnlineStatus( m_protocol->Offline );
		disconnected( Manual ); // cannot use ConnectionReset since that will auto-reconnect
		return;
	}
	else if( succ == Yahoo::LoginVerify )
	{
		initConnectionSignals( DeleteConnections );
		static_cast<YahooContact *>( myself() )->setOnlineStatus( m_protocol->Offline );
		YahooVerifyAccount *verifyDialog = new YahooVerifyAccount( this );
		verifyDialog->setUrl( KURL(url) );
		verifyDialog->show();
		return;
	}

	//If we get here, something went wrong, so set ourselves to offline
	static_cast<YahooContact *>( myself() )->setOnlineStatus( m_protocol->Offline );
	disconnected( Unknown );
}

void YahooAccount::slotDisconnected()
{
	kdDebug(YAHOO_GEN_DEBUG) ;
	initConnectionSignals( DeleteConnections );
	setupActions( false );
	if( !isConnected() )
		return;
	static_cast<YahooContact *>( myself() )->setOnlineStatus( m_protocol->Offline );
	disconnected( ConnectionReset );	// may reconnect

	TQString message;
	message = i18n( "%1 has been disconnected.\nError message:\n%2 - %3" )
		.arg( accountId() ).arg( m_session->error() ).arg( m_session->errorString() );
	KNotification::event( "connection_lost", message, myself()->onlineStatus().protocolIcon() );
}

void YahooAccount::slotLoginFailed()
{
	kdDebug(YAHOO_GEN_DEBUG) ;
	initConnectionSignals( DeleteConnections );
	static_cast<YahooContact *>( myself() )->setOnlineStatus( m_protocol->Offline );
	disconnected( Manual );			// don't reconnect

	TQString message;
	message = i18n( "There was an error while connecting %1 to the Yahoo server.\nError message:\n%2 - %3" )
		.arg( accountId()).arg( m_session->error() ).arg( m_session->errorString() );
	KNotification::event( "cannot_connect", message, myself()->onlineStatus().protocolIcon() );
}

void YahooAccount::slotError( int level )
{
	// enum LogLevel { Debug, Info, Notice, Warning, Error, Critical };
	if( level <= Client::Notice )
		return;
	else if( level <= Client::Warning )
		KMessageBox::information( Kopete::UI::Global::mainWidget(),
			i18n( "%1\n\nReason: %2").arg( m_session->errorInformation() ).arg( m_session->errorString() ),
			i18n( "Yahoo Plugin" ) );
	else
		KMessageBox::error( Kopete::UI::Global::mainWidget(), i18n( "%1\n\nReason: %2" )
			.arg( m_session->errorInformation() ).arg(  m_session->errorString() ), i18n( "Yahoo Plugin" ) );
}

void YahooAccount::slotGotBuddy( const TQString &userid, const TQString &alias, const TQString &group )
{
	kdDebug(YAHOO_GEN_DEBUG) ;
	IDs[userid] = TQPair<TQString, TQString>(group, alias);

	// Serverside -> local
	if ( !contact( userid ) )
	{
		kdDebug(YAHOO_GEN_DEBUG) << "SS Contact " << userid << " is not in the contact list. Adding..." << endl;
		Kopete::Group *g=Kopete::ContactList::self()->findGroup(group);
		addContact(userid, alias.isEmpty() ? userid : alias, g, Kopete::Account::ChangeKABC);
	}

	// FIXME (same)
	//kdDebug(YAHOO_GEN_DEBUG) << IDs << endl;
}

void YahooAccount::slotBuddyAddResult( const TQString &userid, const TQString &group, bool success )
{
     kdDebug(YAHOO_GEN_DEBUG) << success << endl;

     if(success)
	  IDs[userid] = TQPair<TQString, TQString>(group, TQString());

	// FIXME (same)
	//kdDebug(YAHOO_GEN_DEBUG) << IDs << endl;
}

void YahooAccount::slotBuddyRemoveResult( const TQString &userid, const TQString &group, bool success )
{
     kdDebug(YAHOO_GEN_DEBUG);

     // Ignore success here, the only reason this will fail is because the
     // contact isn't on the server's list, so we shouldn't have them in our
     // list either.
     IDs.remove(userid);

	// FIXME
	// kdDebug(YAHOO_GEN_DEBUG) << IDs << endl;
}

void YahooAccount::slotBuddyChangeGroupResult(const TQString &userid, const TQString &group, bool success)
{
     kdDebug(YAHOO_GEN_DEBUG);

     if(success)
	  IDs[userid] = TQPair<TQString, TQString>(group, TQString());

	// FIXME
	//kdDebug(YAHOO_GEN_DEBUG) << IDs << endl;
}

void YahooAccount::slotAuthorizationAccepted( const TQString &who )
{
	kdDebug(YAHOO_GEN_DEBUG) ;
	TQString message;
	message = i18n( "User %1 has granted your authorization request." ).arg( who );
	KNotification::event( TQString::fromLatin1("kopete_authorization"), message );

	if( contact( who ) )
		contact( who )->setOnlineStatus( m_protocol->Online );
}

void YahooAccount::slotAuthorizationRejected( const TQString &who, const TQString &msg )
{
	kdDebug(YAHOO_GEN_DEBUG) ;
	TQString message;
	message = i18n( "User %1 has rejected your authorization request.\n%2" )
		.arg( who ).arg( msg );
	KNotification::event( TQString::fromLatin1("kopete_authorization"), message );
}

void YahooAccount::slotgotAuthorizationRequest( const TQString &user, const TQString &msg, const TQString &name )
{
	kdDebug(YAHOO_GEN_DEBUG) ;
	Q_UNUSED( msg );
	Q_UNUSED( name );
	YahooContact *kc = contact( user );
	Kopete::MetaContact *metaContact=0L;
	if(kc)
		metaContact=kc->metaContact();

	// FIXME: to check
	//Kopete::AddedInfoEvent::ShowActionOptions actions = Kopete::AddedInfoEvent::AuthorizeAction;
	//actions |= Kopete::AddedInfoEvent::BlockAction;
	//if( !metaContact || metaContact->isTemporary() )
	//	actions |= Kopete::AddedInfoEvent::AddAction;

	//Kopete::AddedInfoEvent* event = new Kopete::AddedInfoEvent( user, this );
	//TQObject::connect( event, TQT_SIGNAL(actionActivated(uint)),
	//                  this, TQT_SLOT(slotAddedInfoEventActionActivated(uint)) );

	//event->showActions( actions );
	//event->sendEvent();

	int hideFlags=Kopete::UI::ContactAddedNotifyDialog::InfoButton;
	if( metaContact && !metaContact->isTemporary() )
			hideFlags |= Kopete::UI::ContactAddedNotifyDialog::AddCheckBox | Kopete::UI::ContactAddedNotifyDialog::AddGroupBox ;

	Kopete::UI::ContactAddedNotifyDialog *dialog=
			new Kopete::UI::ContactAddedNotifyDialog( user,TQString(),this, hideFlags );
	TQObject::connect(dialog,TQT_SIGNAL(applyClicked(const TQString&)),
			this,TQT_SLOT(slotContactAddedNotifyDialogClosed(const TQString& )));
	dialog->show();
}


void YahooAccount::slotContactAddedNotifyDialogClosed( const TQString &user )
{
	const Kopete::UI::ContactAddedNotifyDialog *dialog =
		dynamic_cast<const Kopete::UI::ContactAddedNotifyDialog *>(sender());
	if(!dialog || !isConnected())
		return;
	
	m_session->sendAuthReply( user, dialog->authorized(), TQString() );
	
	if(dialog->added())
	{
		dialog->addContact();
	}
}


/*void YahooAccount::slotAddedInfoEventActionActivated( uint actionId )
{
	const Kopete::AddedInfoEvent *event = dynamic_cast<const Kopete::AddedInfoEvent *>(sender());
	if( !event || !isConnected() )
		return;

	switch ( actionId )
	{
	case Kopete::AddedInfoEvent::AuthorizeAction:
		m_session->sendAuthReply( event->contactId(), true, TQString() );
		break;
	case Kopete::AddedInfoEvent::BlockAction:
		m_session->sendAuthReply( event->contactId(), false, TQString() );
		break;
	case Kopete::AddedInfoEvent::AddContactAction:
		event->addContact();
		break;
	}
}*/

void YahooAccount::slotGotIgnore( const TQStringList & /* igns */ )
{
	//kdDebug(YAHOO_GEN_DEBUG) ;
}

void YahooAccount::slotGotIdentities( const TQStringList & /* ids */ )
{
	//kdDebug(YAHOO_GEN_DEBUG) ;
}

void YahooAccount::slotStatusChanged( const TQString &who, int stat, const TQString &msg, int away, int idle, int pictureChecksum )
{
	kdDebug(YAHOO_GEN_DEBUG) << who << " status: " << stat << " msg: " << msg << " away: " << away << " idle: " << idle << endl;
	YahooContact *kc = contact( who );

	if( contact( who ) == myself() )
		return;

	if ( kc )
	{
		Kopete::OnlineStatus newStatus = m_protocol->statusFromYahoo( stat );
		Kopete::OnlineStatus oldStatus = kc->onlineStatus();

		if( newStatus == m_protocol->Custom ) {
			if( away == 0 )
				newStatus =m_protocol->Online;
			kc->setProperty( m_protocol->awayMessage, msg);
		}
		else
			kc->removeProperty( m_protocol->awayMessage );

		// from original file
		if( newStatus != m_protocol->Offline && oldStatus == m_protocol->Offline && contact(who) != myself() )
		{
			//m_session->requestBuddyIcon( who );           // Try to get Buddy Icon

			if ( !myself()->property( Kopete::Global::Properties::self()->photo() ).isNull() &&
					myself()->onlineStatus() != m_protocol->Invisible &&
					!kc->stealthed() )
			{
				kc->sendBuddyIconUpdate( m_session->pictureFlag() );
				kc->sendBuddyIconChecksum( myself()->property( YahooProtocol::protocol()->iconCheckSum ).value().toInt() );
			}
		}

		//if( newStatus == static_cast<YahooProtocol*>( m_protocol )->Idle ) {
		if( newStatus == m_protocol->Idle )
			kc->setIdleTime( idle ? idle : 1 );
		else
			kc->setIdleTime( 0 );

		kc->setOnlineStatus( newStatus );

		slotGotBuddyIconChecksum( who, pictureChecksum );
	}
}

void YahooAccount::slotStealthStatusChanged( const TQString &who, Yahoo::StealthStatus state )
{
	//kdDebug(YAHOO_GEN_DEBUG) << "Stealth Status of " << who << "changed to " << state;

	YahooContact* kc = contact( who );
	if ( kc == NULL ) {
		kdDebug(YAHOO_GEN_DEBUG) << "contact " << who << " doesn't exist." << endl;
		return;
	}
	kc->setStealthed( state == Yahoo::StealthActive );
}

TQString YahooAccount::prepareIncomingMessage( const TQString &messageText )
{
	TQString newMsgText( messageText );
	TQRegExp regExp;
	int pos = 0;
	newMsgText = stripMsgColorCodes( newMsgText );

	kdDebug(YAHOO_GEN_DEBUG) << "Message after stripping color codes '" << newMsgText << "'" << endl;

	newMsgText.replace( TQString::fromLatin1( "&" ), TQString::fromLatin1( "&amp;" ) );

	// Replace Font tags
	regExp.setMinimal( true );
	regExp.setPattern( "<font([^>]*)size=\"([^>]*)\"([^>]*)>" );
	pos = 0;
	while ( pos >= 0 ) {
		pos = regExp.search( newMsgText, pos );
		if ( pos >= 0 ) {
			pos += regExp.matchedLength();
		newMsgText.replace( regExp, TQString::fromLatin1("<font\\1style=\"font-size:\\2pt\">" ) );
		}
	}

	// Remove FADE and ALT tags
	regExp.setPattern( "<[/]*FADE([^>]*)>" );
	pos = 0;
	while ( pos >= 0 ) {
		pos = regExp.search( newMsgText, pos );
		if ( pos >= 0 ) {
			pos += regExp.matchedLength();
			newMsgText.remove( regExp );

		}
	}
	regExp.setPattern( "<[/]*ALT([^>]*)>" );
	pos = 0;
	while ( pos >= 0 ) {
		pos = regExp.search( newMsgText, pos );
		if ( pos >= 0 ) {
			pos += regExp.matchedLength();
			newMsgText.remove( regExp );
		}
	}

	// Replace < and > in text
	regExp.setPattern( "<(?!(/*(font.*|[\"fbui])>))" );
	pos = 0;
	while ( pos >= 0 ) {
		pos = regExp.search( newMsgText, pos );
		if ( pos >= 0 ) {
			pos += regExp.matchedLength();
			newMsgText.replace( regExp, TQString::fromLatin1("&lt;" ) );
		}
	}
	regExp.setPattern( "([^\"bui])>" );
	pos = 0;
	while ( pos >= 0 ) {
		pos = regExp.search( newMsgText, pos );
		if ( pos >= 0 ) {
			pos += regExp.matchedLength();
			newMsgText.replace( regExp, TQString::fromLatin1("\\1&gt;" ) );
		}
	}

	// add closing tags when needed
	regExp.setMinimal( false );
	regExp.setPattern( "(<b>.*)(?!</b>)" );
	newMsgText.replace( regExp, TQString::fromLatin1("\\1</b>" ) );
	regExp.setPattern( "(<i>.*)(?!</i>)" );
	newMsgText.replace( regExp, TQString::fromLatin1("\\1</i>" ) );
	regExp.setPattern( "(<u>.*)(?!</u>)" );
	newMsgText.replace( regExp, TQString::fromLatin1("\\1</u>" ) );
	regExp.setPattern( "(<font.*)(?!</font>)" );
	newMsgText.replace( regExp, TQString::fromLatin1("\\1</font>" ) );

	newMsgText.replace( TQString::fromLatin1( "\r" ), TQString::fromLatin1( "<br/>" ) );

	return newMsgText;
}

void YahooAccount::slotGotIm( const TQString &who, const TQString &msg, long tm, int /*stat*/)
{
	TQFont msgFont;
	TQDateTime msgDT;
	Kopete::ContactPtrList justMe;

	if( !contact( who ) )
	{
		kdDebug(YAHOO_GEN_DEBUG) << "Adding contact " << who << endl;
		addContact( who,who,  0L, Kopete::Account::Temporary );
	}

	//Parse the message for it's properties
	kdDebug(YAHOO_GEN_DEBUG) << "Original message is '" << msg << "'" << endl;
	//kdDebug(YAHOO_GEN_DEBUG) << "Message color is " << getMsgColor(msg);
	TQColor fgColor = getMsgColor( msg );

	// FIXME to check
	if (tm == 0)
		//msgDT = TQDateTime( TQDate::currentDate(), TQTime::currentTime(), TQt::LocalTime );
		msgDT.setTime_t(time(0L));
	else
		//msgDT = TQDateTime::fromTime_t(tm);
		msgDT.setTime_t(tm, Qt::LocalTime);

	TQString newMsgText = prepareIncomingMessage( msg );

	kdDebug(YAHOO_GEN_DEBUG) << "Message after fixing font tags '" << newMsgText << "'" << endl;

	Kopete::ChatSession *mm = contact(who)->manager(Kopete::Contact::CanCreate);

	// Tell the message manager that the buddy is done typing
	mm->receivedTypingMsg(contact(who), false);

	justMe.append(myself());

	Kopete::Message kmsg(msgDT, contact(who), justMe, newMsgText,
		Kopete::Message::Inbound , Kopete::Message::RichText);

	kmsg.setFg( fgColor );
	mm->appendMessage(kmsg);
}

void YahooAccount::slotGotBuzz( const TQString &who, long tm )
{
	TQFont msgFont;
	TQDateTime msgDT;
	Kopete::ContactPtrList justMe;

	if( !contact( who ) )
	{
		kdDebug(YAHOO_GEN_DEBUG) << "Adding contact " << who << endl;
		addContact( who,who,  0L, Kopete::Account::Temporary );
	}

	// FIXME: to check
	if (tm == 0)
		//msgDT = TQDateTime( TQDate::currentDate(), TQTime::currentTime(), TQt::LocalTime );
		msgDT.setTime_t(time(0L));
	else
		//msgDT = TQDateTime::fromTime_t(tm);
		msgDT.setTime_t(tm, Qt::LocalTime);

	justMe.append(myself());

	TQString buzzMsgText = i18n("This string is shown when the user is buzzed by a contact", "Buzz");

	Kopete::Message kmsg(msgDT, contact(who), justMe, buzzMsgText, Kopete::Message::Inbound,
		Kopete::Message::PlainText, TQString(), Kopete::Message::TypeAction);

	TQColor fgColor( "gold" );
	kmsg.setFg( fgColor );

	Kopete::ChatSession *mm = contact(who)->manager(Kopete::Contact::CanCreate);
	mm->appendMessage(kmsg);
	// Emit the buzz notification.
	mm->emitNudgeNotification();
}

void YahooAccount::slotGotConfInvite( const TQString & who, const TQString & room, const TQString &msg, const TQStringList &members )
{
	kdDebug(YAHOO_GEN_DEBUG) << who << " has invited you to join the conference \"" << room << "\" : " << msg << endl;
	kdDebug(YAHOO_GEN_DEBUG) << "Members: " << members << endl;

	if( !m_pendingConfInvites.contains( room ) )	// We have to keep track of the invites as the server will send the same invite twice if it gets canceled by the host
		m_pendingConfInvites.push_back( room );
	else
	{
		return;
	}

	TQString m = who;
	TQStringList myMembers;
	myMembers.push_back( who );
	for( TQStringList::const_iterator it = ++members.constBegin(); it != members.constEnd(); ++it )
	{
		if( *it != m_session->userId() )
		{
			m.append( TQString(", %1").arg( *it ) );
			myMembers.push_back( *it );
		}
	}
	if( KMessageBox::Yes == KMessageBox::questionYesNo( Kopete::UI::Global::mainWidget(),
		i18n("%1 has invited you to join a conference with %2.\n\nHis/her message: %3\n\nAccept?")
		.arg(who).arg(m).arg(msg), TQString(), i18n("Accept"), i18n("Ignore") ) )
	{
		m_session->joinConference( room, myMembers );
		if( !m_conferences[room] )
		{
			Kopete::ContactPtrList others;
			YahooConferenceChatSession *session = new YahooConferenceChatSession( room, protocol(), myself(), others );
			m_conferences[room] = session;

			TQObject::connect( session, TQT_SIGNAL(leavingConference( YahooConferenceChatSession * ) ), this, TQT_SLOT( slotConfLeave( YahooConferenceChatSession * ) ) );

			for ( TQStringList::ConstIterator it = myMembers.constBegin(); it != myMembers.constEnd(); ++it )
			{
				YahooContact * c = contact( *it );
				if ( !c )
				{
					kdDebug(YAHOO_GEN_DEBUG) << "Adding contact " << *it << " to conference." << endl;
					addContact( *it,*it,  0L, Kopete::Account::Temporary );
					c = contact( *it );
				}
				session->joined( c );
			}
			session->view( true )->raise( false );
		}
	}
	else
		m_session->declineConference( room, myMembers, TQString() );

	m_pendingConfInvites.remove( room );
}

void YahooAccount::prepareConference( const TQString &who )
{
	TQString room;
	for( int i = 0; i < 22; i++ )
	{
		char c = rand()%52;
		room += (c > 25)  ? c + 71 : c + 65;
	}
	room = TQString("%1-%2--").arg(accountId()).arg(room);
	kdDebug(YAHOO_GEN_DEBUG) << "The generated roomname is: " << room << endl;

	TQStringList buddies;

	// FIXME: to check
	//TQHash<TQString,Kopete::Contact*>::ConstIterator it, itEnd = contacts().constEnd();
	//for( it = contacts().constBegin(); it != itEnd; ++it )
	//{
	//	buddies.push_back( it.value()->contactId() );
	//}

	TQDictIterator<Kopete::Contact> it( contacts() );
	for( ; it.current(); ++it )
	{
		if( (*it) != myself() )
			buddies.push_back( (*it)->contactId() );
	}

	YahooInviteListImpl *dlg = new YahooInviteListImpl( Kopete::UI::Global::mainWidget() );
	TQObject::connect( dlg, TQT_SIGNAL( readyToInvite( const TQString &, const TQStringList &, const TQStringList &, const TQString & ) ),
			this, TQT_SLOT( slotInviteConference( const TQString &, const TQStringList &, const TQStringList &, const TQString & ) ) );
	dlg->setRoom( room );
	dlg->fillFriendList( buddies );
	dlg->addInvitees( TQStringList( who ) );
	dlg->show();
}

void YahooAccount::slotInviteConference( const TQString &room, const TQStringList &members, const TQStringList &participants, const TQString &msg )
{
	Q_UNUSED( participants );
kdDebug(YAHOO_GEN_DEBUG) << "Inviting " << members << " to the conference " << room << ". Message: " << msg << endl;
	m_session->inviteConference( room, members, msg );

	Kopete::ContactPtrList others;
	YahooConferenceChatSession *session = new YahooConferenceChatSession( room, protocol(), myself(), others );
	m_conferences[room] = session;

	TQObject::connect( session, TQT_SIGNAL(leavingConference( YahooConferenceChatSession * ) ), this, TQT_SLOT( slotConfLeave( YahooConferenceChatSession * ) ) );

	session->joined( static_cast< YahooContact *>(myself()) );
	session->view( true )->raise( false );
}

void YahooAccount::slotAddInviteConference( const TQString &room, const TQStringList &who, const TQStringList &members, const TQString &msg )
{
	kdDebug(YAHOO_GEN_DEBUG) << "Inviting " << who << " to the conference " << room << ". Message: " << msg << endl;
	m_session->addInviteConference( room, who, members, msg );
}

void YahooAccount::slotConfUserDecline( const TQString &who, const TQString &room, const TQString &msg)
{
	kdDebug(YAHOO_GEN_DEBUG) ;

	if( !m_conferences.contains( room ) )
	{
		kdDebug(YAHOO_GEN_DEBUG) << "Error. No chatsession for this conference found." << endl;
		return;
	}

	YahooConferenceChatSession *session = m_conferences[room];

	TQString body = i18n( "%1 has declined to join the conference: \"%2\"").arg( who ).arg( msg );
    Kopete::Message message = Kopete::Message( contact( who ), myself(), body, Kopete::Message::Internal, Kopete::Message::PlainText );

	session->appendMessage( message );
}

void YahooAccount::slotConfUserJoin( const TQString &who, const TQString &room )
{
	kdDebug(YAHOO_GEN_DEBUG) ;
	if( !m_conferences.contains( room ) )
	{
		kdDebug(YAHOO_GEN_DEBUG) << "Error. No chatsession for this conference found." << endl;
		return;
	}

	YahooConferenceChatSession *session = m_conferences[room];
	if( !contact( who ) )
	{
		addContact( who, who,  0L, Kopete::Account::Temporary );
	}
	session->joined( contact( who ) );
}

void YahooAccount::slotConfUserLeave( const TQString & who, const TQString &room )
{
	kdDebug(YAHOO_GEN_DEBUG) ;
	if( !m_conferences.contains( room ) )
	{
		kdDebug(YAHOO_GEN_DEBUG) << "Error. No chatsession for this conference found." << endl;
		return;
	}

	YahooConferenceChatSession *session = m_conferences[room];
	if( !contact( who ) )
	{
		addContact( who, who,  0L, Kopete::Account::Temporary );
	}
	session->left( contact( who ) );
}

void YahooAccount::slotConfLeave( YahooConferenceChatSession *s )
{
	kdDebug(YAHOO_GEN_DEBUG) ;
	if( !s )
		return;
	TQStringList members;
	for( Kopete::ContactPtrList::ConstIterator it = s->members().constBegin(); it != s->members().constEnd(); ++it )
	{
		if( (*it) == myself() )
			continue;
		kdDebug(YAHOO_GEN_DEBUG) << "Member: " << (*it)->contactId() << endl;
		members.append( (*it)->contactId() );
	}
	m_session->leaveConference( s->room(), members );
	m_conferences.remove( s->room() );
}

void YahooAccount::slotConfMessage( const TQString &who, const TQString &room, const TQString &msg )
{
	kdDebug(YAHOO_GEN_DEBUG) ;

	if( !m_conferences.contains( room ) )
	{
		kdDebug(YAHOO_GEN_DEBUG) << "Error. No chatsession for this conference found." << endl;
		return;
	}

	YahooConferenceChatSession *session = m_conferences[room];

	TQFont msgFont;
	TQDateTime msgDT;
	Kopete::ContactPtrList justMe;

	if( !contact( who ) )
	{
		kdDebug(YAHOO_GEN_DEBUG) << "Adding contact " << who << endl;
		addContact( who,who,  0L, Kopete::Account::Temporary );
	}
	kdDebug(YAHOO_GEN_DEBUG) << "Original message is '" << msg << "'" << endl;

	TQColor fgColor = getMsgColor( msg );
	msgDT.setTime_t(time(0L));

	TQString newMsgText = prepareIncomingMessage( msg );

	kdDebug(YAHOO_GEN_DEBUG) << "Message after fixing font tags '" << newMsgText << "'" << endl;
	session->receivedTypingMsg(contact(who), false);

	justMe.append(myself());

	Kopete::Message kmsg(msgDT, contact(who), justMe, newMsgText,
		Kopete::Message::Inbound , Kopete::Message::RichText);

	kmsg.setFg( fgColor );
	session->appendMessage(kmsg);
}

void YahooAccount::sendConfMessage( YahooConferenceChatSession *s, const Kopete::Message &message )
{
	kdDebug(YAHOO_GEN_DEBUG) ;
	TQStringList members;
	for( Kopete::ContactPtrList::ConstIterator it = s->members().constBegin(); it != s->members().constEnd(); ++it )
	{
		if( (*it) == myself() )
			continue;
		kdDebug(YAHOO_GEN_DEBUG) << "Member: " << (*it)->contactId() << endl;
		members.append( (*it)->contactId() );
	}
	m_session->sendConferenceMessage( s->room(), members, YahooContact::prepareMessage( message.escapedBody() ) );
}

void YahooAccount::slotGotYABRevision( long rev, bool merged )
{
	if( merged )
	{
		kdDebug(YAHOO_GEN_DEBUG) << "Merge Revision received: " << rev << endl;
		configGroup()->writeEntry( "YABLastMerge", (TQ_INT64)rev );
		m_YABLastMerge = rev;
	}
	else
	{
		kdDebug(YAHOO_GEN_DEBUG) << "Remote Revision received: " << rev << endl;
		configGroup()->writeEntry( "YABLastRemoteRevision", (TQ_INT64)rev );
		m_YABLastRemoteRevision = rev;
	}
}

void YahooAccount::slotGotYABEntry( YABEntry *entry )
{
	YahooContact* kc = contact( entry->yahooId );
	if( !kc )
	{
		kdDebug(YAHOO_GEN_DEBUG) << "YAB entry received for a contact not on our buddylist: " << entry->yahooId << endl;
		delete entry;
	}
	else
	{
		kdDebug(YAHOO_GEN_DEBUG) << "YAB entry received for: " << entry->yahooId << endl;
		if( entry->source == YABEntry::SourceYAB )
		{
			kc->setYABEntry( entry );
		}
		else if( entry->source == YABEntry::SourceContact )
		{
			entry->YABId = kc->yabEntry()->YABId;
			YahooUserInfoDialog *dlg = new YahooUserInfoDialog( kc, Kopete::UI::Global::mainWidget() );
			dlg->setData( *entry );
			dlg->setAccountConnected( isConnected() );
			dlg->show();
			TQObject::connect( dlg, TQT_SIGNAL(saveYABEntry( YABEntry & )), this, TQT_SLOT(slotSaveYABEntry( YABEntry & )));
			delete entry;
		}
	}
}

void YahooAccount::slotSaveYABEntry( YABEntry &entry )
{
	kdDebug(YAHOO_GEN_DEBUG) << "YABId: " << entry.YABId << endl;
	if( entry.YABId > 0 )
		m_session->saveYABEntry( entry );
	else
		m_session->addYABEntry( entry );
}

void YahooAccount::slotModifyYABEntryError( YABEntry *entry, const TQString &msg )
{
	YahooContact* kc = contact( entry->yahooId );
	if( kc )
		kc->setYABEntry( entry, true );
	KMessageBox::queuedMessageBox( Kopete::UI::Global::mainWidget(), KMessageBox::Sorry, msg, i18n( "Yahoo Plugin" ) );
}

void YahooAccount::slotGotFile( const TQString &  who, const TQString &  url , long /* expires */, const TQString &  msg , const TQString &  fname, unsigned long  fesize, const TQPixmap &preview )
{
	kdDebug(YAHOO_GEN_DEBUG) << "Received File from " << who << ": " << msg << endl;
	kdDebug(YAHOO_GEN_DEBUG) << "Filename :" << fname << " size:" << fesize << endl;

	// FIXME: preview?
	Kopete::TransferManager::transferManager()->askIncomingTransfer( contact( who ) , fname, fesize, msg, url /* , preview */ );

	if( m_pendingFileTransfers.empty() )
	{
	TQObject::connect( Kopete::TransferManager::transferManager(), TQT_SIGNAL( accepted( Kopete::Transfer *, const TQString& ) ),
					this, TQT_SLOT( slotReceiveFileAccepted( Kopete::Transfer *, const TQString& ) ) );
	TQObject::connect( Kopete::TransferManager::transferManager(), TQT_SIGNAL( refused(const Kopete::FileTransferInfo& ) ),
	                  this, TQT_SLOT( slotReceiveFileRefused( const Kopete::FileTransferInfo& ) ) );
	}
	m_pendingFileTransfers.append( url );
}

void YahooAccount::slotReceiveFileAccepted(Kopete::Transfer *transfer, const TQString& fileName)
{
	kdDebug(YAHOO_GEN_DEBUG) ;
	if( !m_pendingFileTransfers.contains( transfer->info().internalId() ) )
		return;

	m_pendingFileTransfers.remove( transfer->info().internalId() );

	// FIXME to check
	//Create directory if it doesn't already exist
	TQDir dir;
	TQString path = TQFileInfo( fileName ).dirPath();
	for( int i = 1; i <= path.contains('/'); ++i )
	{
		if( !dir.exists( path.section( '/', 0, i ) ) )
		{
				dir.mkdir( path.section( '/', 0, i) );
		}
	}

	m_session->receiveFile( transfer->info().transferId(), transfer->info().contact()->contactId(), transfer->info().internalId(), fileName );
	m_fileTransfers.insert( transfer->info().transferId(), transfer );
	TQObject::connect( transfer, TQT_SIGNAL(result( TDEIO::Job * )), this, TQT_SLOT(slotFileTransferResult( TDEIO::Job * )) );

	if( m_pendingFileTransfers.empty() )
	{
		TQObject::disconnect( Kopete::TransferManager::transferManager(), TQT_SIGNAL( accepted( Kopete::Transfer *, const TQString& ) ),
							this, TQT_SLOT( slotReceiveFileAccepted( Kopete::Transfer *, const TQString& ) ) );
		TQObject::disconnect( Kopete::TransferManager::transferManager(), TQT_SIGNAL( refused(const Kopete::FileTransferInfo& ) ),
						this, TQT_SLOT( slotReceiveFileRefused( const Kopete::FileTransferInfo& ) ) );
	}
}

void YahooAccount::slotReceiveFileRefused( const Kopete::FileTransferInfo& info )
{
	if( !m_pendingFileTransfers.contains( info.internalId() ) )
		return;

	m_pendingFileTransfers.remove( info.internalId() );
	m_session->rejectFile( info.contact()->contactId(), info.internalId() );

	if( m_pendingFileTransfers.empty() )
	{
		TQObject::disconnect( Kopete::TransferManager::transferManager(), TQT_SIGNAL( accepted( Kopete::Transfer *, const TQString& ) ),
							this, TQT_SLOT( slotReceiveFileAccepted( Kopete::Transfer *, const TQString& ) ) );
		TQObject::disconnect( Kopete::TransferManager::transferManager(), TQT_SIGNAL( refused(const Kopete::FileTransferInfo& ) ),
						this, TQT_SLOT( slotReceiveFileRefused( const Kopete::FileTransferInfo& ) ) );
	}
}

void YahooAccount::slotFileTransferBytesProcessed( unsigned int transferId, unsigned int bytes )
{
	kdDebug(YAHOO_GEN_DEBUG) << "Transfer: " << transferId << " Bytes:" << bytes << endl;
	Kopete::Transfer *t = m_fileTransfers[transferId];
	if( !t )
		return;

	t->slotProcessed( bytes );
}

void YahooAccount::slotFileTransferComplete( unsigned int transferId )
{
	kdDebug(YAHOO_GEN_DEBUG) ;
	Kopete::Transfer *t = m_fileTransfers[transferId];
	if( !t )
		return;

	t->slotComplete();
	m_fileTransfers.remove( transferId );
}

void YahooAccount::slotFileTransferError( unsigned int transferId, int error, const TQString &desc )
{
	kdDebug(YAHOO_GEN_DEBUG) ;
	Kopete::Transfer *t = m_fileTransfers[transferId];
	if( !t )
		return;

	t->slotError( error, desc );
	m_fileTransfers.remove( transferId );
}

void YahooAccount::slotFileTransferResult( TDEIO::Job *job )
{
	kdDebug(YAHOO_GEN_DEBUG) ;
	const Kopete::Transfer *t = dynamic_cast< const Kopete::Transfer * >( job );

	if( !t )
		return;

	if( t->error() == TDEIO::ERR_USER_CANCELED )
	{
		m_session->cancelFileTransfer( t->info().transferId() );
		m_fileTransfers.remove( t->info().transferId() );
	}
}

void YahooAccount::slotContactAdded( const TQString & /* myid */, const TQString & /* who */, const TQString & /* msg */ )
{
//	kdDebug(YAHOO_GEN_DEBUG) << myid << " " << who << " " << msg;
}

void YahooAccount::slotRejected( const TQString & /* who */, const TQString & /* msg */ )
{
//	kdDebug(YAHOO_GEN_DEBUG) ;
}

void YahooAccount::slotTypingNotify( const TQString &who, int what )
{
	emit receivedTypingMsg(who, what);
}

void YahooAccount::slotGameNotify( const TQString & /* who */, int /* stat */ )
{
//	kdDebug(YAHOO_GEN_DEBUG) ;
}

void YahooAccount::slotMailNotify( const TQString& from, const TQString&  subject , int cnt )
{
	kdDebug(YAHOO_GEN_DEBUG) << "Mail count: " << cnt << endl;

	if ( cnt > 0 && from.isEmpty() )
	{
		TQObject::connect(KNotification::event( TQString::fromLatin1("yahoo_mail"), i18n( "You have one unread message in your Yahoo inbox.",
			"You have %n unread messages in your Yahoo inbox.", cnt ), TQPixmap() , 0 ),
			TQT_SIGNAL(activated(unsigned int ) ) , this, TQT_SLOT( slotOpenInbox() ) );

		m_currentMailCount = cnt;
	}
	else if ( cnt > 0 )
	{	kdDebug(YAHOO_GEN_DEBUG) << "attempting to trigger event" << endl;

		TQObject::connect(KNotification::event( TQString::fromLatin1("yahoo_mail"), i18n( "You have a message from %1 in your Yahoo inbox. <br><br>Subject: %2").arg( from ).arg( subject ),
			TQPixmap() , 0 ), TQT_SIGNAL(activated(unsigned int ) ) , this, TQT_SLOT( slotOpenInbox() ) );

		m_currentMailCount = cnt;
	}
}

void YahooAccount::slotSystemMessage( const TQString & /* msg */ )
{
//	kdDebug(YAHOO_GEN_DEBUG) << msg;
}

void YahooAccount::slotRemoveHandler( int /* fd */ )
{
//	kdDebug(YAHOO_GEN_DEBUG) ;
}

void YahooAccount::slotGotWebcamInvite( const TQString& who )
{
	YahooContact* kc = contact( who );
	if ( kc == NULL ) {
		kdDebug(YAHOO_GEN_DEBUG) << "contact " << who << " doesn't exist." << endl;
		return;
	}

	if( m_pendingWebcamInvites.contains( who ) )
		return;

	m_pendingWebcamInvites.append( who );

	if( KMessageBox::Yes == KMessageBox::questionYesNo( Kopete::UI::Global::mainWidget(), i18n("%1 has invited you to view his/her webcam. Accept?").arg( who ),
                            TQString(), i18n("Accept"), i18n("Ignore") ) )
	{
		m_pendingWebcamInvites.remove( who );
		m_session->requestWebcam( who );
	}
}
void YahooAccount::slotWebcamNotAvailable( const TQString &who )
{
	KMessageBox::queuedMessageBox( Kopete::UI::Global::mainWidget(), KMessageBox::Sorry, i18n("Webcam for %1 is not available.").arg(who), i18n( "Yahoo Plugin" ) );
}

void YahooAccount::slotGotWebcamImage( const TQString& who, const TQPixmap& image )
{
	YahooContact* kc = contact( who );
	if ( kc == NULL ) {
		kdDebug(YAHOO_GEN_DEBUG) << "contact " << who << " doesn't exist." << endl;
		return;
	}
	kc->receivedWebcamImage( image );
}

void YahooAccount::slotPictureStatusNotify( const TQString &who, int status)
{
	YahooContact *kc = contact( who );
	if ( kc == NULL ) {
		kdDebug(YAHOO_GEN_DEBUG) << "contact " << who << " doesn't exist." << endl;
		return;
	}

	kdDebug(YAHOO_GEN_DEBUG) << "contact " << who << " changed picture status to" << status << endl;
}

void YahooAccount::slotGotBuddyIconChecksum(const TQString &who, int checksum)
{
	YahooContact *kc = contact( who );
	if ( kc == NULL ) {
		kdDebug(YAHOO_GEN_DEBUG) << "contact " << who << " doesn't exist." << endl;
		return;
	}

	if ( checksum == kc->property( YahooProtocol::protocol()->iconCheckSum ).value().toInt() &&
	     TQFile::exists( locateLocal( "appdata", "yahoopictures/"+ who.lower().replace(TQRegExp("[./~]"),"-")  +".png" ) ) )
	{
		kdDebug(YAHOO_GEN_DEBUG) << "Icon already exists. I will not request it again." << endl;
		return;
	} else
		m_session->requestPicture( who );
}

void YahooAccount::slotGotBuddyIconInfo(const TQString &who, KURL url, int checksum)
{
	kdDebug(YAHOO_GEN_DEBUG) ;
	YahooContact *kc = contact( who );
	if ( kc == NULL ) {
		kdDebug(YAHOO_GEN_DEBUG) << "contact " << who << " doesn't exist." << endl;
		return;
	}

	if ( checksum == kc->property( YahooProtocol::protocol()->iconCheckSum ).value().toInt()  &&
	     TQFile::exists( locateLocal( "appdata", "yahoopictures/"+ who.lower().replace(TQRegExp("[./~]"),"-")  +".png" ) ))
	{
		kdDebug(YAHOO_GEN_DEBUG) << "Icon already exists. I will not download it again." << endl;
		return;
	} else
		m_session->downloadPicture( who, url, checksum );
}

void YahooAccount::slotGotBuddyIcon( const TQString &who, const TQByteArray &data, int checksum )
{
	kdDebug(YAHOO_GEN_DEBUG) << k_funcinfo << endl;
	YahooContact *kc = contact( who );
	if ( kc == NULL ) {
		kdDebug(YAHOO_GEN_DEBUG) << "contact " << who << " doesn't exist." << endl;
		return;
	}
	kc->setDisplayPicture( data, checksum );
}
void YahooAccount::slotGotBuddyIconRequest( const TQString & who )
{
	kdDebug(YAHOO_GEN_DEBUG) ;
	m_session->sendPictureInformation( who, myself()->property( YahooProtocol::protocol()->iconRemoteUrl ).value().toString(),
	                                   myself()->property( YahooProtocol::protocol()->iconCheckSum ).value().toInt() );
}

void YahooAccount::setBuddyIcon( const KURL &url )
{
	kdDebug(YAHOO_GEN_DEBUG) << "Url: " << url.path() << endl;
	TQString s = url.path();
	if ( url.path().isEmpty() )
	{
		myself()->removeProperty( Kopete::Global::Properties::self()->photo() );
		myself()->removeProperty( YahooProtocol::protocol()->iconRemoteUrl );
		myself()->removeProperty( YahooProtocol::protocol()->iconExpire );

		if ( m_session )
			m_session->setPictureStatus( Yahoo::NoPicture );
	}
	else
	{
		TQImage image( url.path() );
		TQString newlocation( locateLocal( "appdata", "yahoopictures/"+ url.fileName().lower() ) ) ;
		TQFile iconFile( newlocation );
		TQByteArray data;
		uint expire = myself()->property( YahooProtocol::protocol()->iconExpire ).value().toInt();

		if ( image.isNull() ) {
			KMessageBox::queuedMessageBox( Kopete::UI::Global::mainWidget(), KMessageBox::Sorry, i18n( "<qt>The selected buddy icon could not be opened. <br />Please set a new buddy icon.</qt>" ), i18n( "Yahoo Plugin" ) );
			return;
		}
		image = image.smoothScale( 96, 96, TQ_ScaleMin );
		if(image.width() < image.height())
		{
			image = image.copy((image.width()-image.height())/2, 0, 96, 96);
		}
		else if(image.height() < image.width())
		{
			image = image.copy(0, (image.height()-image.width())/2, 96, 96);
		}

		if( !image.save( newlocation, "PNG" ) || !iconFile.open(IO_ReadOnly) )
		{
			KMessageBox::queuedMessageBox( Kopete::UI::Global::mainWidget(), KMessageBox::Sorry, i18n( "An error occurred when trying to change the display picture." ), i18n( "Yahoo Plugin" ) );
			return;
		}

		data = iconFile.readAll();
		iconFile.close();

		// create checksum - taken from qhash.cpp of qt4
		const uchar *p = reinterpret_cast<const uchar *>(data.data());
		int n = data.size();
		uint checksum = 0;
		uint g;
		while (n--)
		{
			checksum = (checksum << 4) + *p++;
			if ((g = (checksum & 0xf0000000)) != 0)
				checksum ^= g >> 23;
			checksum &= ~g;
		}

		myself()->setProperty( Kopete::Global::Properties::self()->photo() , newlocation );
		configGroup()->writeEntry( "iconLocalUrl", newlocation );

		if ( checksum != static_cast<uint>(myself()->property( YahooProtocol::protocol()->iconCheckSum ).value().toInt()) ||
		     TQDateTime::currentDateTime().toTime_t() > expire )
		{
			myself()->setProperty( YahooProtocol::protocol()->iconCheckSum, checksum );
			configGroup()->writeEntry( "iconCheckSum", checksum );
			if ( m_session != 0 )
				m_session->uploadPicture( newlocation );
		}
	}
}

void YahooAccount::slotBuddyIconChanged( const TQString &url, int expires )
{
	kdDebug(YAHOO_GEN_DEBUG) ;
	int checksum = myself()->property( YahooProtocol::protocol()->iconCheckSum ).value().toInt();

	if( !url.isEmpty() )
	{
		myself()->setProperty( YahooProtocol::protocol()->iconRemoteUrl, url );
		myself()->setProperty( YahooProtocol::protocol()->iconExpire , expires );
		configGroup()->writeEntry( "iconRemoteUrl", url );
		configGroup()->writeEntry( "iconExpire", expires );
		m_session->setPictureStatus( Yahoo::Picture );
		m_session->sendPictureChecksum( TQString(), checksum );
	}
}

void YahooAccount::slotWebcamReadyForTransmission()
{
	kdDebug(YAHOO_GEN_DEBUG) ;
	if( !m_webcam )
	{
		m_webcam = new YahooWebcam( this );
		TQObject::connect( m_webcam, TQT_SIGNAL(webcamClosing()), this, TQT_SLOT(slotOutgoingWebcamClosing()) );
	}

	m_webcam->startTransmission();
}

void YahooAccount::slotWebcamStopTransmission()
{
	kdDebug(YAHOO_GEN_DEBUG) ;

	if( m_webcam )
	{
		m_webcam->stopTransmission();
	}
}

void YahooAccount::slotOutgoingWebcamClosing()
{
	m_session->closeOutgoingWebcam();
	m_webcam->deleteLater();
	m_webcam = 0L;
}

void YahooAccount::slotWebcamViewerJoined( const TQString &viewer )
{
	if( m_webcam )
	{
		m_webcam->addViewer( viewer );
	}
}

void YahooAccount::slotWebcamViewerRequest( const TQString &viewer )
{
	if( KMessageBox::Yes == KMessageBox::questionYesNo( Kopete::UI::Global::mainWidget(), i18n("%1 wants to view your webcam. Grant access?")
		.arg(viewer), TQString(), i18n("Accept"), i18n("Ignore") ) )
		m_session->grantWebcamAccess( viewer );
}

void YahooAccount::slotWebcamViewerLeft( const TQString &viewer )
{
	if( m_webcam )
	{
		m_webcam->removeViewer( viewer );
	}
}

void YahooAccount::slotWebcamClosed( const TQString& who, int reason )
{
	YahooContact* kc = contact( who );
	if ( kc == NULL ) {
		kdDebug(YAHOO_GEN_DEBUG) << "contact " << who << " doesn't exist." << endl;
		return;
	}
	kc->webcamClosed( reason );
}

void YahooAccount::slotWebcamPaused( const TQString &who )
{
	YahooContact* kc = contact( who );
	if ( kc == NULL ) {
		kdDebug(YAHOO_GEN_DEBUG) << "contact " << who << " doesn't exist." << endl;
		return;
	}
	kc->webcamPaused();
}

void YahooAccount::setOnlineStatus( const Kopete::OnlineStatus &status, const TQString &reason)
{
	kdDebug(YAHOO_GEN_DEBUG) ;
	if ( myself()->onlineStatus().status() == Kopete::OnlineStatus::Offline &&
	     status.status() != Kopete::OnlineStatus::Offline )
	{
		if( !reason.isEmpty() )
			m_session->setStatusMessageOnConnect( reason );
		connect( status );
	}
	else if ( myself()->onlineStatus().status() != Kopete::OnlineStatus::Offline &&
	          status.status() == Kopete::OnlineStatus::Offline )
	{
		disconnect();
	}
	else if ( myself()->onlineStatus().status() != Kopete::OnlineStatus::Offline &&
	          status.internalStatus() == 2 && !reason.isEmpty())
	{
		slotGoStatus( 99, reason );
	}
	else if ( myself()->onlineStatus().status() != Kopete::OnlineStatus::Offline &&
	          status.internalStatus() == 99 && reason.isEmpty())
	{
		slotGoStatus( 2, reason );
	}
	else if ( myself()->onlineStatus().status() != Kopete::OnlineStatus::Offline )
	{
		slotGoStatus( status.internalStatus(), reason );
	}
}

/* FIXME: not ported yet
void YahooAccount::setStatusMessage(const Kopete::StatusMessage &statusMessage)
{
	int currentStatus = myself()->onlineStatus().internalStatus();
	m_session->changeStatus( Yahoo::Status( currentStatus ), statusMessage.message(),
	                         (currentStatus == Yahoo::StatusAvailable)? Yahoo::StatusTypeAvailable : Yahoo::StatusTypeAway );
	myself()->setStatusMessage( statusMessage );
}
*/

void YahooAccount::slotOpenInbox()
{
	KRun::runURL( KURL( TQString::fromLatin1("http://mail.yahoo.com/") ) , "text/html" );
}

void YahooAccount::slotOpenYAB()
{
	KRun::runURL( KURL( TQString::fromLatin1("http://address.yahoo.com/") ) , "text/html" );
}

void YahooAccount::slotEditOwnYABEntry()
{
	myself()->slotUserInfo();
}

// FIXME: not ported yet
void YahooAccount::slotJoinChatRoom()
{
}
/*
	YahooChatSelectorDialog *chatDialog = new YahooChatSelectorDialog( Kopete::UI::Global::mainWidget() );

	TQObject::connect( m_session, TQT_SIGNAL(gotYahooChatCategories( const TQDomDocument & )), chatDialog,
					TQT_SLOT(slotSetChatCategories( const TQDomDocument & )) );
	TQObject::connect( m_session, TQT_SIGNAL(gotYahooChatRooms( const Yahoo::ChatCategory &, const TQDomDocument & )),
					chatDialog, TQT_SLOT(slotSetChatRooms( const Yahoo::ChatCategory &, const TQDomDocument & )) );
	TQObject::connect( chatDialog, TQT_SIGNAL(chatCategorySelected( const Yahoo::ChatCategory & )),
					this, TQT_SLOT(slotChatCategorySelected( const Yahoo::ChatCategory & ) ) );
	m_session->getYahooChatCategories();

	if( chatDialog->exec() == TQDialog::Accepted )
	{
		kdDebug() << chatDialog->selectedRoom().topic << " " << chatDialog->selectedRoom().topic << " " << chatDialog->selectedRoom().id << endl;
		m_session->joinYahooChatRoom( chatDialog->selectedRoom() );
	}

	chatDialog->deleteLater();
}
*/

void YahooAccount::slotLeavChat()
{
	m_chatChatSession = 0;
	m_session->leaveChat();
}

void YahooAccount::slotChatCategorySelected( const Yahoo::ChatCategory &category )
{
	m_session->getYahooChatRooms( category );
}

// FIXME: not ported yet
void YahooAccount::slotChatJoined( int roomId, int categoryId, const TQString &comment, const TQString &handle )
{
}
/*
	Kopete::ContactPtrList others;
	others.append(myself());

	if( !m_chatChatSession )
	{
		m_chatChatSession = new YahooChatChatSession( protocol(), myself(), others );
		TQObject::connect( m_chatChatSession, TQT_SIGNAL(closing(Kopete::ChatSession *)), this,
					TQT_SLOT(slotLeavChat()) );
	}
	m_chatChatSession->removeAllContacts();
	m_chatChatSession->setHandle( handle );
	m_chatChatSession->setTopic( handle );

	m_chatChatSession->view( true )->raise( false );

	Kopete::Message msg( myself(), m_chatChatSession->members() );
	msg.setHtmlBody( i18n("You are now in %1 (%2)", handle, comment) );
	msg.setDirection( Kopete::Message::Internal );

	m_chatChatSession->appendMessage( msg );
}
*/

// FIXME: not ported yet
void YahooAccount::slotChatBuddyHasJoined( const TQString &nick, const TQString &handle, bool suppressNotification )
{
}
/*
	if(!m_chatChatSession)
		return;

	if( !m_chatChatSession->handle().startsWith( handle ) )
		return;

	YahooContact *c = contact( nick );
	if ( !c )
	{
		kdDebug(YAHOO_GEN_DEBUG) << "Adding contact " << nick << " to chat." << endl;
// 		addContact( nick, nick, 0, Kopete::Account::Temporary );
		if( !createChatContact( nick ) )
			return;
		c = contact( nick );
		c->setOnlineStatus( m_protocol->Online );
	}
	m_chatChatSession->joined( c, suppressNotification );
}
*/

// FIXME: not ported yet
void YahooAccount::slotChatBuddyHasLeft( const TQString &nick, const TQString &handle )
{
}
/*
	kdDebug(YAHOO_GEN_DEBUG) ;

	if(!m_chatChatSession)
		return;

	if( !m_chatChatSession->handle().startsWith( handle ) )
		return;

	YahooContact *c = contact( nick );
	if( !c )
		return;
	m_chatChatSession->left( c );
}
*/

// FIXME: not ported yet
void YahooAccount::slotChatMessageReceived( const TQString &nick, const TQString &message, const TQString &handle )
{
}
/*
	if(!m_chatChatSession)
		return;

	if( !m_chatChatSession->handle().startsWith( handle ) )
		return;

	TQFont msgFont;
	TQDateTime msgDT;
	Kopete::ContactPtrList justMe;

	if( !contact( nick ) )
	{
		kdDebug(YAHOO_GEN_DEBUG) << "Adding contact " << nick << endl;
		addContact( nick, nick, 0, Kopete::Account::DontChangeKABC );
		if( !createChatContact( nick ) )
			return;
	}
	kdDebug(YAHOO_GEN_DEBUG) << "Original message is '" << message << "'" << endl;

	TQColor fgColor = getMsgColor( message );
	msgDT.setTime_t(time(0L));

	TQString newMsgText = prepareIncomingMessage( message );

	kdDebug(YAHOO_GEN_DEBUG) << "Message after fixing font tags '" << newMsgText << "'" << endl;

	justMe.append(myself());

	Kopete::Message kmsg( contact(nick), justMe );
	kmsg.setTimestamp( msgDT );
	kmsg.setHtmlBody( newMsgText );
	kmsg.setDirection( Kopete::Message::Inbound );

	kmsg.setForegroundColor( fgColor );
	m_chatChatSession->appendMessage(kmsg);
}
*/

void YahooAccount::sendChatMessage( const Kopete::Message &msg, const TQString &handle )
{
	m_session->sendYahooChatMessage( YahooContact::prepareMessage( msg.escapedBody() ), handle );
}


#include "yahooaccount.moc"

// vim: set noet ts=4 sts=4 sw=4:
//kate: indent-mode csands; tab-width 4;