#ifndef _KVI_CONSOLE_H_
#define _KVI_CONSOLE_H_
//=============================================================================
//
//   File : kvi_console.h
//   Creation date : Sun Jun 25 2000 15:00:20 by Szymon Stefanek
//
//   This file is part of the KVirc irc client distribution
//   Copyright (C) 1999-2000 Szymon Stefanek (stefanek@tin.it)
//
//   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 opinion) any later version.
//
//   This program 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. ,59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
//=============================================================================

#include "kvi_settings.h"
#include "kvi_window.h"
#include "kvi_irclink.h"
#include "kvi_string.h"
#include "kvi_lagmeter.h"
#include "kvi_wstring.h"

#include "kvi_list.h"

#include <time.h>

class QToolBar;
class QToolButton;

class KviAvatar;
class KviDns;
class KviIrcUserDataBase;
class KviIrcUserEntry;
class KviIrcServer;
class KviIrcNetwork;
class KviProxy;
#ifndef COMPILE_ON_WINDOWS
	class KviChannel;
	class KviQuery;
#else
	// windoze wants it to compile QList<KviChannel> and QList<KviQuery>
	#include "kvi_channel.h"
	#include "kvi_query.h"
#endif
class KviUserListView;
class KviNotifyListManager;
//class KviIrcContextController;
class KviExternalServerDataParser;
class KviRegisteredUser;
class KviLagMeter;

typedef struct _KviWhoisInfo
{
	KviStr szNick;
	KviStr szUser;
	KviStr szHost;
	KviStr szReal;
	KviStr szServer;
	KviStr szIdle;
	KviStr szSignon;
	KviStr szChannels;
	KviStr szSpecial;
	KviStr szCode;
	KviStr szMagic;
	KviWindow * pWindow;
} KviWhoisInfo;


class KviConnectionInfo
{
public:
	KviConnectionInfo(KviIrcNetwork * net,KviIrcServer * srv,KviProxy * prx);
	~KviConnectionInfo();
public:
	KviStr                        szNetworkName;              // selected at connect time
	KviIrcServer                * pIrcServer;                 // current irc server (local copy) (never 0)
	KviProxy                    * pProxy;                     // current proxy (local copy if non 0)
	KviStr                        szBindAddress;              // address to bind the local machine to
	bool                          bSentQuit;                  // sent the quit message ?
	KviDns                      * pDns;                       // non 0 if resolving a host
	int                           iNicknameUsed;              // loginToIrcServer()
	KviStr                        szLocalHostIp;              // resolveLocalHost()
	KviIrcUserDataBase          * pUserDataBase;              // local user database
	KviNotifyListManager        * pNotifyListManager;         // restartNotifyList()
	KviStr                        szRealName;                 // the one sent to the server at login
	KviStr                        szNickName;                 // the current one         
	KviStr                        szUserMode;                 // the current one
	KviStr                        szLocalHostFromServer;      // local host from server
	KviStr                        szUserNameFromServer;       // username from server (with ident chars)
	KviStr                        szServerNameFromServer;     // the server wants to be known as
	KviStr                        szServerSupportedUserModes;
	KviStr                        szServerSupportedChanModes;
	KviStr                        szCommandToExecAfterConnect;
	bool                          bServerSupportsModeIe;
	bool                          bServerSupportsWatchList;

	QTimer                      * pNotifyListTimer;           // delayed startup timer for the notify lists

	KviPtrList<KviChannel>      * pChannelList;
	KviPtrList<KviQuery>        * pQueryList;

	KviStr                        szLastNetsplit;
	time_t                        lastNetsplitTime;

	KviPtrList<KviWhoisInfo>    * pWhoisInfoList;             // awhois pending stuff

	time_t                        lastCtcpTime;
	unsigned int                  uCtcpCount;

	bool                          bAway;
	time_t                        tAwayTime;
	KviStr                        szNickBeforeAway;
public:
	KviChannel                  * findChannel(const char * name);
	KviQuery                    * findQuery(const char * nick);
	KviIrcUserDataBase          * userDataBase(){ return pUserDataBase; };

};

typedef struct KviAsyncServerCommandData
{
	KviStr             szServer;
	unsigned short int uPort;
	bool               bPortIsOk;
	bool               bUseIpV6;
	bool               bUseSSL;
	KviStr             szBindAddress; // ip address (or interface name) to bind the connection to
	KviStr             szCommandToExecAfterConnect;
	KviStr             szLinkFilter;
	KviStr             szPass;
	KviStr             szNick;
    KviStr             szInitUMode;
} KviAsyncServerCommandData;

//=================================================================================================
//
// The console window
//
//=================================================================================================

#define KVI_CONSOLE_FLAG_FIRSTINAPP 1
#define KVI_CONSOLE_FLAG_FIRSTINFRAME 2

class KVIRC_API KviConsole : public KviWindow
{
	friend class KviFrame;
	friend class KviIrcLink;
	friend class KviChannel;
	friend class KviQuery;
	friend class KviIrcLinkMonitor;
	Q_OBJECT
public:
	enum ConnectionState { Connecting , LoggingIn , Connected , NotConnected };

	KviConsole(KviFrame * lpFrm,unsigned int uId,const char * name,int iFlags);
	~KviConsole();
protected:
	int                                m_iFlags; // FIXME: make this a KviWindow property ?
	unsigned int                       m_uIrcContextId;

//	KviConnection                    * m_pConnection;

	KviIrcLink                       * m_pLink;
	KviConnectionInfo                * m_pConnectionInfo;
	ConnectionState                    m_state;
	KviUserListView                  * m_pNotifyListView;
	QToolButton                      * m_pNotifyViewButton;
//	KviIrcContextController          * m_pIcController;
	KviPtrList<KviIrcLinkMonitor>    * m_pMonitorList;
	KviExternalServerDataParser      * m_pLinksWindow;
	KviExternalServerDataParser      * m_pListWindow;
	QString                            m_szStatusString; // nick (flags) on server | not connected
	// This stuff is used for the SERVER command
	KviAsyncServerCommandData        * m_pAsyncServerCommandData;

	KviPtrList<KviChannel>           * m_pDeadChannels;
	KviPtrList<KviQuery>             * m_pDeadQueries;
    KviLagMeter                      * m_pLagMeter;

protected:
	virtual QPixmap * myIconPtr();
	virtual void fillCaptionBuffers();
	virtual void resizeEvent(QResizeEvent *e);
	virtual void closeEvent(QCloseEvent *e);
	virtual void getBaseLogFileName(KviStr &buffer);
	virtual void fillContextPopup(QPopupMenu * p);
	virtual QSize sizeHint() const;
	virtual void applyOptions();
	virtual void triggerCreationEvents();
	void linkEvent(KviIrcLink::LinkEvent ev,void * arg);
	void registerLinkMonitor(KviIrcLinkMonitor * m);
	void unregisterLinkMonitor(KviIrcLinkMonitor * m);

	void closeAllDeadChannels();
	void closeAllDeadQueries();
	bool unregisterDeadChannel(KviChannel * c);
	bool unregisterDeadQuery(KviQuery * q);
	void registerDeadChannel(KviChannel * c);
	void registerDeadQuery(KviQuery * q);
	void setChannelAsDead(KviChannel * c);
	void setQueryAsDead(KviQuery * q);
	void setChannelAsAlive(KviChannel * c);
	void setQueryAsAlive(KviQuery * q);

//	void createConnectionInfo(KviIrcNetwork * net,KviIrcServer * srv,KviProxy * prx);
	void keepChannelsOpenAfterDisconnect();
	void keepQueriesOpenAfterDisconnect();
	void resurrectDeadQueries();
	void destroyConnection();
	void destroyAsyncServerCommandData();
	void haveServerIp();
	void lookupServerHostname();
	void lookupProxyHostname();
	void setState(ConnectionState st);
	void resolveLocalHost();
	void loginToIrcServer();
	void registerQuery(KviQuery *q);
	void registerChannel(KviChannel *c);
	void unregisterQuery(KviQuery *q);
	void unregisterChannel(KviChannel *c);
	void startNotifyList();
//	void destroyDnsObject(KviDns * d);
//	void triggerCreationEvents(bool bTriggerOnFrameCreated = false);
	bool validateLocalAddress(const char * szAddress,KviStr &szBuffer);
	KviIrcLink * getLinkFilter(const char * nam);
	virtual void linkSuicideRequest(KviIrcLink * l);
public:
	//
	// State
	//
	KviConsole::ConnectionState state(){ return m_state; };
	unsigned int ircContextId(){ return m_uIrcContextId; };
	KviConnectionInfo * connection(){ return m_pConnectionInfo; };
	//
	// Sock state
	//
	KviIrcLink * link(){ return m_pLink; };
	bool isConnected(){ return (m_state == Connected); };
	bool isIpV6Connection();
	bool isNotConnected(){ return (m_state == NotConnected); };
	bool connectionInProgress(){ return ((m_state != NotConnected) || (m_pAsyncServerCommandData != 0)); };
	//
	// Socket monitors
	//
//	KviPtrList<KviIrcLinkMonitor> * ircSocketMonitors(){ return m_pServerLinkMonitorList; };
//	void registerSocketMonitor(KviIrcLinkMonitor * m);
//	void unregisterSocketMonitor(KviIrcLinkMonitor *m);
	//
	// This connection info
	//
	KviConnectionInfo * connectionInfo(){ return m_pConnectionInfo; };
	const char * currentNickName(){ return (m_pConnectionInfo ? m_pConnectionInfo->szNickName.ptr() : KviStr::emptyString().ptr()); };
	const char * currentUserName(){ return (m_pConnectionInfo ? m_pConnectionInfo->szUserNameFromServer.ptr() : KviStr::emptyString().ptr()); };
	const char * currentUserMode(){ return (m_pConnectionInfo ? m_pConnectionInfo->szUserMode.ptr() : KviStr::emptyString().ptr()); };
	const char * currentLocalHostName(){ return (m_pConnectionInfo ? m_pConnectionInfo->szLocalHostFromServer.ptr() : KviStr::emptyString().ptr()); };
	const char * currentServerName(){ return (m_pConnectionInfo ? m_pConnectionInfo->szServerNameFromServer.ptr() : KviStr::emptyString().ptr()); };
	const char * currentNetworkName(){ return (m_pConnectionInfo ? m_pConnectionInfo->szNetworkName.ptr() : KviStr::emptyString().ptr()); };
	KviAvatar * currentAvatar();
	//
	// UI internals
	//
	void createLinksWindow();
	void createListWindow();
	void setLinksWindowPointer(KviExternalServerDataParser * l){ m_pLinksWindow = l; };
	void setListWindowPointer(KviExternalServerDataParser * l){ m_pListWindow = l; };
	KviExternalServerDataParser * linksWindow(){ return m_pLinksWindow; };
	KviExternalServerDataParser * listWindow(){ return m_pListWindow; };
//	KviIrcContextController * icController(){ return m_pIcController; };
	virtual void loadProperties(KviConfig * cfg);
	virtual void saveProperties(KviConfig * cfg);
	KviUserListView * notifyListView(){ return m_pNotifyListView; };
	//
	// IRC Context wide helpers (connection related)
	//
	int getCommonChannels(const char * nick,KviStr &chansBuffer,bool bEscapeSeq = true);
	void getUserTipText(const char * nick,KviIrcUserEntry *e,KviStr &buffer);
	void outputPrivmsg(KviWindow *wnd,int type,const char *nick,
		const char *user,const char *host,const char *msg);
	// Avatar helpers (conneciton related)
	void resetAvatarForMatchingUsers(KviRegisteredUser * u);
	// this should be protected at least
	void avatarChangedUpdateWindows(const char * nick,const char * textLine);
	void avatarChanged(KviAvatar * avatar,const char * nick,const char * user,const char * host,const char * textLine);
	void setAvatar(const char * nick,const char * user,const char * host,const char * fName);
	void checkDefaultAvatar(KviIrcUserEntry *e,const char * nick,const char *user,const char * host);
	// Away (connection related)
	void changeAwayState(bool bAway);
	bool userIsAway(){ return m_pConnectionInfo ? m_pConnectionInfo->bAway : false; };
	// Async whois stuff (Connection related)
	void addAsyncWhois(KviWhoisInfo * i){ m_pConnectionInfo->pWhoisInfoList->append(i); };
	KviWhoisInfo * lookupAsyncWhois(const char * nick);
	void removeAsyncWhois(KviWhoisInfo * i){ m_pConnectionInfo->pWhoisInfoList->removeRef(i); };

	void setAsyncServerCommandData(KviAsyncServerCommandData * d);
	void connectToCurrentServer();
	void loginComplete(const char * servNick);
	void terminateConnectionRequest(bool bForce = false,const char * quitMsg = 0);

	// User mode (connection related)
	bool hasUserMode(char c){ return (m_pConnectionInfo ? m_pConnectionInfo->szUserMode.contains(c) : false); };
	bool userModeEmpty(){ return (m_pConnectionInfo ? m_pConnectionInfo->szUserMode.isEmpty() : true); };
	bool setUserMode(char mode,bool bSet);
	// Status string (usermode + nick) (connection related too)
	const QString & statusString(){ return m_szStatusString; };
	// Channel and query window managements (connection related)
	KviQuery * createQuery(const char * name);
	KviChannel * createChannel(const char * name);
	KviPtrList<KviChannel> * channelList(){ return m_pConnectionInfo ? m_pConnectionInfo->pChannelList : 0; };
	KviPtrList<KviQuery> * queryList(){ return m_pConnectionInfo ? m_pConnectionInfo->pQueryList : 0; };
	unsigned int channelCount(){ return (m_pConnectionInfo ? m_pConnectionInfo->pChannelList->count() : 0); };
	unsigned int queryCount(){ return (m_pConnectionInfo ? m_pConnectionInfo->pQueryList->count() : 0); };
	// Window management
	KviChannel * findChannel(const char * name){ return connection() ? connection()->findChannel(name) : 0; };
	KviChannel * findDeadChannel(const char * name);
	KviQuery * findDeadQuery(const char * nick);
	KviQuery * findQuery(const char * nick){ return connection() ? connection()->findQuery(nick) : 0; };
	KviQuery * findQueryByName(const char * nick);
	KviWindow * activeWindow();
	// User db, connection related
	KviIrcUserDataBase * userDataBase(){ return m_pConnectionInfo ? m_pConnectionInfo->pUserDataBase : 0; };
	void setUserInfoFromServer(const char * username,const char *localhost);
	void setServerInfoFromServer(const char * servname,const char * umodes,const char * chanmodes);
	void nickChange(const char * newNick);
	void completeChannel(const KviStr &word,KviPtrList<KviStr> * matches);
	// Monitors
	bool hasMonitors(){ return m_pMonitorList != 0; };
	KviPtrList<KviIrcLinkMonitor> * monitorList(){ return m_pMonitorList; };
    KviLagMeter * lagMeter(){ return m_pLagMeter; };

public slots:
	void restartNotifyList();
	void asyncServerCommand();
	void executeInternalCommand(int index);
	void connectButtonClicked();
protected slots:
	void toggleNotifyView();
	void textViewRightClicked();
	void serverLookupTerminated(KviDns *);
	void proxyLookupTerminated(KviDns *);
	void closeAllChannels();
	void closeAllQueries();
	void partAllChannels();
signals:
	void stateChange(KviConsole::ConnectionState newState);
};

#endif //_KVI_CONSOLE_H_
