/***************************************************************************
 *   Copyright (C) 2008 by SK Communications.                              *
 *   http://kldp.net/projects/nateon/                                      *
 *                                                                         *
 *   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 3 of the License, or     *
 *   (at your option) 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.             *
 ***************************************************************************/

#ifndef _KNATEON_H_
#define _KNATEON_H_

#include "config.h"

#include <kaboutdata.h>
#include <klocale.h>
#include <qsize.h>
#include <kdebug.h>
#include <kmessagebox.h>
#include <kapp.h>
#include <qlayout.h>
#include <qdatetime.h>
#include <quuid.h>
#include <qregexp.h>
#include <qmap.h>
#include <qptrlist.h>
#include <kmessagebox.h>
#include <qhttp.h>
#include <qbuffer.h>
#include <qurl.h>
#include <qwidgetstack.h>
#include <dcopclient.h>
#include <qasciidict.h>
#include <kiconloader.h>

#include "knateonview.h"
#include "knateondcop.h"
#include "chat/memopopupview.h"

//forward declaration
class QHBox;
class QLabel;
class KActionMenu;
class KConfig;
class KHelpMenu;
class KLed;
class KMessTest;
class KPopupMenu;
class KSelectAction;
class KToggleAction;
class LoginView;
class LogoutView;
class NetworkWindow;
class NateonDPLConnection;
class NateonDPConnection;
class Account;
class CurrentAccount;
class KNateonMainview;
class ChatView;
class MemoPopupView;
class ChatList;
class CurrentAccount;
class SystemTrayWidget;
class MemoView;
class MemoList;
class InputBox;
class AddFriendView;
class CommandQueue;
class AllowAddFriend;
class PreferenceView;
class P2PServer;
class SendFileInfo;
class Common;
class FileTransfer;
class ToastWindow;
class WebViewer;
class InviteWeb;
class IdleTimer;
class XAutoLock;
class KNateOnDCOP;
class SQLiteDB;
class Preference;
class PopupWindow;
class WebCGI;
class PostCGI;
class BuddyList;
class GroupList;
class DeleteForm;
class ContactRoot;
class MimeMessage;
class Emoticon;
class Buddy;
class SSConnection;
class Group;
class NOMP2PList;
class NOMP2PBase;

// class ServerSocket;

/**
 * @short Application Main Window
 * @author Doo-Hyun Jang <ring0320@nate.com>
 * @version 0.1
 */
class KNateon : public KNateonInterface, virtual KNateOnDCOP
{
    Q_OBJECT
    public:
    /**
     * Default Constructor
     */
	KNateon ( KApplication *parent, QWidget* widget = 0, const char *name = 0 );
    /**
     * Default Destructor
     */
	virtual ~KNateon();
  
	bool initialize();
	bool initializeLoginView();
	bool initializeLogoutView();
	bool initializeNateonDPLConnection();
	bool initializeNateonDPConnection();
	bool initializeNetworkWindow();
	bool initializeMainView();
	bool initializeSystemTray();
	bool initIdleTimer();
	bool sendMemo ( QString sSender, QString sRef, QString sMemo );
	void changeStatusOnline();
	void dcopCommand( const QString s );
	void saveUserDB();
	void setDefaultWebBrowser();
	void reqAddFriend(QString sID, QString sInviteMsg, bool bShowMsgBox = true);
  
protected:
	KActionMenu     *connectActionMenu_;
	KAction         *disconnect_;
	KSelectAction   *status_;
	KActionMenu     *settingsActionMenu_;
	void resizeEvent ( QResizeEvent *e );
	void closeEvent ( QCloseEvent * e );
  
private:
	void readProperties ( KConfig *config );
	void saveProperties ( KConfig *config );
	ChatView* createChat ( int nTID );
  
	QHttp*                m_pHttp;
	QBuffer*              m_pWebBuffer;
	LoginView*            m_pLoginView;
	LogoutView*           m_pLogoutView;
	KNateonMainview*      m_pMainView;
	NateonDPLConnection*  m_pDPLcon;
	NateonDPConnection*   m_pDPcon;
	NetworkWindow*        m_pNetworkWindow;
	CurrentAccount*       m_pCurrentAccount;
    /// 대화창 관리.
	ChatList*             m_pChatList;
	SystemTrayWidget*     systemTrayWidget_;
    /// 쪽지창 관리.
	MemoList*             m_pMemoList;
    /// 그룹 추가
	InputBox*             m_pAddGroupInputBox;
    /// 그룹 이름변경
	InputBox*             m_pRenameGroupInputBox;
  
    /// 그룹명을 추가 하고, tid로 그룹 id값을 받는다.
	typedef QMap<int, QString> mapTidGroup;
	mapTidGroup mapGroup;
  
	AddFriendView*          m_pAddFriend;
	AllowAddFriend*         m_pAllowAddFriend;
	QPtrList<CommandQueue>  m_CommandQueue;
	Preference/*PreferenceView*/*         m_pPreferenceView;
    /// 파일 전송을 위한 접속 서버.
	P2PServer*              m_pP2PServer;
	Common*                 m_pCommon;
    /// 파일 전송 창.
	FileTransfer*           m_pFileTransfer;
  
	int                     nREQC;
	KAction*                pLoginAction;
  
	void showFileTransferDialog ( SendFileInfo* pSendFileInfo );
  
	ToastWindow*            pToastWindow;
	WebViewer*              pWebViewer;
	InviteWeb*              pInviteWeb;
	PopupWindow*            pPopup;
	PopupWindow*            pMemoPopup;
	PopupWindow*            pChatPopup;
	PopupWindow*            pMemoNotify;
	PopupWindow*		pMailPopup;
	int                     nPopupX;
	int                     nPopupY;
	bool bCancelFileTransfer;
  
    /*! {ID, 초대메시지} */
	typedef QMap<QString, QString> mapGetInviteMsg;
	mapGetInviteMsg mapInvite;
	// quitSelected   (   )
	IdleTimer*              idleTimer_;
	QTimer*                 m_pMemoPopupTimer;
	QTimer*                 m_pC1C2Timer;
	QTimer*	m_pRetryConnectTimer;
	WebCGI*                 pMemoCountCGI;
	WebCGI*                 pMemoGetCGI;
	WebCGI*                 pProfileGetCGI;
	WebCGI*                 pFixBuddyCGI;
	PostCGI*                 pMajorHompyCGI;
	PostCGI*                 pHompyNewCGI;
    /*! 환경설정 */
	KConfig*                config;
  
    /*! 쪽지, 대화용 SQLite3 */
	SQLiteDB*               pSQLiteDB;
	QString sMemoDataPath;
	QString sChatDataPath;
	QString sDataPath;
//     QString sP2PDataPath;
    
	QString sDCOPTempCommand;
  
	bool bIsConnected;
  
	int nCySync;
  
	BuddyList* m_pBuddyList;
	GroupList* m_pGroupList;
	
	/*! 종료 필드 */
	bool bQuit;

	/*! 이모티콘 변환 클래스 */
	Emoticon*               pEmoticon;
  
	/*! 그룹명 임시 저장 함수 */
	QString sTempAddGroupName;

	/*! 메모 띄우기 */
	// MemoPopupView *pMemo1;1

	/*! 친구 삭제 다이얼로그 */
	DeleteForm *pDeleteForm;

	/*! 온라인 오프라인 정보 */
	bool bOnline;

	/*! 로그아웃메뉴선택? */
	bool bLogout;
	
	/*! 접속이 되었나? */
	bool bConnect;

	// char cSaveStatus;
	bool bIdle;
	
	/*! wallet 객체 */
	//KWallet *mWallet;
	
	QString sPicsPath;

    /*! 파일전송 리스트 */
    QPtrList<NOMP2PBase> m_P2PList;
    QPtrList<SendFileInfo> m_P2PFileInfoList;
    
    NOMP2PList *m_pP2PList;
    // ServerSocket *m_pP2PServerSocket;

    QIntDict<QStringList> m_SaveTID;

    bool isP2PActivedFileCookie( const QString & sFileCookie );
    bool isP2PActivedP2PCookie( const QString & sP2PCookie );
                              
public slots:
	void slotViewMemo ( const QString &sReceiver );
  
private slots:
	void connectWithAccount ( Account *pAccount );
	void connectDPWithAccount ( Account* pAccount );
    // void DPLconnected();
	void DPLdisconnected();
	void connected();
	void disconnected();
	void startChat ( Buddy* pBuddy );
	/*! 그룹 체팅 */
	void slotStartChat ( const ContactRoot* pRoot );
	void startChat ( QPtrList<Buddy>& slBuddies );
	void slotViewChat ( SSConnection* m_SSConnection );
	void slotSendMemo ( MemoView* pMemoView );
	void slotViewMemoPopup ( const MimeMessage& sMemo );
	void slotViewAMemoPopup ( const MimeMessage& sMemo );
	void slotReplyMemo ( MemoPopupView::SendType mSendType, const QString& sReceiver, const QString& sBody );
	void slotAddGroup();
	void slotRenameGroup();
	void slotDeleteGroup();
	void slotInputAddGroup ( QString sGroupName );
	void slotInputRenameGroup ( QString sGroupName );
	void slotGotAddGroup ( const QStringList& slCommand );
    /* void slotViewChat(QListViewItem* m_pSelectQLVI, const QPoint& m_cPointQP, int m_nID); */
	void slotAddFriend();
	void slotAddFriendRequire ( AddFriendView* pAddFriendView );
	void gotINVT ( const QStringList& slCommand );
	void slotSendINVT ( ChatView *pChatView );
	void slotNewConnectSS( ChatView *pChatView );
	void slotAddCommandQueue ( const QStringList& slCommand );
    // void slotConnectToP2P(const QStringList& slCommand);
	void slotErr201();
	void slotErr300();
	void slotErr301( const QStringList& );
	void slotErr302();
	void slotErr306();
	void slotErr309();
	void slotErr421();
	void slotErr500( const QStringList & );
	void slotErr998( const QStringList & );
	void slotDisconnected();
	void slotLSIN();
	void slotDPLError421();
	
	/// 환경설정
	void slotSetup();
	
	void slotNetLog();
    /// 파일전송
	void slotSendFile ( SendFileInfo* pSendFileInfo );
	void slotREQCNEW ( ChatView* pChat, SendFileInfo* pSendFileInfo );
	void slotREFR ( SendFileInfo* pSendFileInfo );
	void slotFileAcceptOk ( SendFileInfo* pSendFileInfo );
	void slotChangeStatusNumber ( int nID );
// 	void finishTransfer( SendFileInfo * pSendFileInfo );

	/*! 채팅 로그를 저장하고 채팅창을 없앤다. */
	void slotChatRemove ( ChatView* pChatView, bool bWriteLog );
  
	/*! 채팅 로그 저장 */
	void slotSaveChatLog( ChatView* pChatView, bool bWriteLog );
  
	void slotChatInviteData ( ChatView* pChatView );
	void slotInviteINVT ( ChatView* pChatView, QStringList& slInvitorList );
  
	void slotGotINFY ( const QStringList& slCommand );
	void slotGotInviteMsg ( QStringList& slCommand );
	void slotAddConfirm ( const QStringList& slCommand );
    // void slotConnectP2PFR( const QStringList& slCommand );
    /*!
      파일 전송을 상대에서 Cancel했을때, WHSP NACK 받았을때
    */
	void slotCancelReceive ( const QStringList& slCommand );

	void slotCancelReceiveAll ( const QStringList& slCommand );
  
    /*!
      P2P 접속시도 중 상대의 RES를 받고 기다리는데 응답이 없으면,
      FR서버 요청을 함.
    */
	void slotP2PTimeOut ( SendFileInfo *pSendFileInfo );
  
    /*!
      FR 서버 정보를 받았을때..
    */
    // void slotReceivedREFR( const QStringList& slCommand );
	void slotSendCTOCFR( SendFileInfo *pSendFileInfo );
  
    /*!
      Nick 변경 환경설정 화면 보임.
    */
	void slotShowChangeNick();
  
    /*!
      온라인 팝업을 클릭해서 채팅을 함.
    */
	void slotClickChatPopup( int nType, QString sID);
  
    /*!
      자리 비움 타이머
    */
	void slotUserIsIdle();
	void slotUserIsNotIdle();
  
    /*!
      메모 개수
    */
	void slotMemoCount( QStringList& slResult );
  
    /*!titleFrameLayout
      받은 메모 저장
    */
	void slotSaveMemo( QStringList& slMemo );

	/*!
	 * 대화함 보기
	 */
	void slotViewChatBox();

	/*!
	 * 지난 대화 보기
	 */
	void slotViewChatLog( const ChatView* pChatView );

	/*!
	 * 쪽지함 보기
	 */
	void slotViewMemoBox();
  
    /*!
      다중선택 버디 사용자 복사 / 이동 / 삭제
    */
	void slotCopyBuddy( const QString & sGroup );
	void slotMoveBuddy( const QString & sGroup );
	void slotDeleteBuddy();
	void slotLoadBuddyList();
	void slotSaveBuddyList();
  
	/*! 버디 블럭 */
	void slotBlockBuddy();
	void slotBlockBuddy( const QString &sID );
  
	/*! 마우스오른쪽/메뉴에서 파일 보내기 */
	void slotMenuSendFile();
  
	/*! Always On Top */
	void slotMenuAlwaysTop( bool bTop );
  
	/*! 리스트 이모티콘 보기 */
	void slotListEmoticon( bool bEmoticon );
  
	/*! 메뉴 - 버디 리스트 보기 선택 */
	void slotNamingSelect( int nType );
	/*! 퀵메뉴에서 버디 이름으로 보기 선택시 */
	void slotBuddyOnlyName();
	void slotBuddyOnlyNick();
	void slotBuddyNameID();
	void slotBuddyNameNick();
  
	/*! 버디 리스트 정렬 선택 */
	void slotBuddySort( int nSort );
	void slotBuddyListAll();
	void slotBuddyListOnline();
	void slotBuddyListOnOff();
  
	void slotAllHide();
  
	void slotHidePopup();
  
	/*! 싸이연동 */
	void slotCySync(const QString &sID, const QString &sPW);
	void slotCPRF( const QStringList & slCommand );
	void slotCyUpdate( const QString &sCommand );

	/*! 버디 닉 변경 */
	void slotNNIK( const QStringList& slCommand );

	/*! 시작시 오프라인 쪽지 개수 팝업을 클릭하면 */
	void slotClickMessageBoxPopup( int nType, QString sID );

	/*! knateon 종료 */
	void slotCloseApp();

	/*! 트레이메뉴 로그인 */
	void slotLogin();

	/*! 싸이월드 메인으로 이동 */
	void slotGoCyMain();

	/*! 내 미니홈피로 이동 */
	void slotGoMyMinihompy();

	/*! DP로 부터 KILL 을 받았을때... */
	void slotKill();
  
	/*! 채팅창이 아웃포커싱일때 팝업창 띄우기 위한... */
	void slotChatMessage( const QStringList& slCommand );

	/*! 채팅 메시지가 오면... */
	void slotIncomingChat(int nType, QString sID);

	/*! 버디리스트에서 CPRF로 변경된 내용이 옴 */
	void slotNPRF( const QStringList& slCommand );
  
	/*! 알람 패킷을 받았을때... */
	void slotALRM( const QStringList& slCommand );

	/*! 버디 알람 패킷을 받았을때... */
	void slotCALM( const QStringList& slCommand );
	
	/*! 쪽지에서 원문표시 설정 */
	void slotMemoSetupReplyRole();

	/*! 재 로그인 */
	void slotRelogin();

	/*! 남몰래 로그인 */
	void slotHidenLogin( bool bHidenLogin );

	/*! 다른 사용자로 로그인 */
	void slotOtherLogin();

	/*! 네이트닷컴 연동 해제 */
	void slotNateSyncCancel();

	/*! 프로필 보기 */
	void slotShowProfile();
  
	/*! 프로필 수정 */
	void slotEditProfile();

	/*! 버디리스트 Refresh */
	void slotRefreshBuddyList();

	/*! 그룹 차단 */
	void slotLockGroup( const QString &sGID );
  
	/*! 그룹 차단 해제 */
	void slotUnlockGroup( const QString &sGID );

	/*!
	 * UUID로 쪽지 보기 창을 띄운다.
	 * 첫번째 인자는 팝업타입으로 MemoIncoming은 3번이다.
	 */
	void slotPopupMemoFromUUID( int nType, QString sUUID );

	/*! 메일 알림 팝업창 클릭 */
	void slotShowNewMail( int nType, QString sUrl );

	/*! 허용된 대화 상대에게만 대화 요청 받기 */
	void slotPrivacyPermitChat( bool bAllow );
  
	/*! 친구에게만 쪽지 받기 */
	void slotPrivacyFriendMemo( bool bAllow );

	/*! 쪽지 팝업띄우기 */
	void slotShowMemoPopup();

	/*! 웹에서 받은 프라이버시 설정관련 내용처리 */
	void slotGetProfile( QStringList& slResult );

	/*! 자리비움 설정 업데이트 */
	void slotUpdateAwayInfo();

	/*! 버디 삭제 다이얼로그 로부터...  */
	void slotDeleteFriend( DeleteForm * pDeleteForm );

	/*! 메모 삭제 */
	void slotDeleteMemo( const QString & sUUID );

	/*! 미니홈피 주계정 정보 가져 오기 */
	void slotMajorHompy( const QString & sResult );

	/*! 주계정 정보 가져오기 */
	void slotC1C2();

	/*! 미니홈피 새글 알림 */
	void slotHompyNew( const QString& sResult );

	/*! 미니홈피 팝업창 클릭 */
	void slotHompyRUrl( const QString &sUrl );

	void slotPingError();

	void slotRetryConnect();
	
	void slotAddEtc( const QString & sID );

	void slotAddBuddyADSB_REQST( const QStringList& slCommand );

	void slotTransferCancel( const QString & sSSCookie );
	void slotMyTransferCancel( const QString & sSSCookie );
	void slotCloseMemoPopup( MemoPopupView * pMemoPopup );
	void slotCloseMemoView( MemoView* pMemoView );

	/*! 전송창 보이기 */
	void slotOpenTransfer();
	
	void slotGoNateDotCom();
	
	/*! 웹 브라우저 변경 */
	void slotChangeWebBrowser( const QString & sBrowser );

    /*! P2P 서버에서 ATHC를 받으면 */
    // void slotP2PServerATHC( const QSocket *pSocket, const QString &sP2PCookie );
//     void slotP2PServerATHC( int nSocket, const QString &sP2PCookie );

    /*! P2P 서버에서 새 클라이언트 접속이 오면, */
    // void slotNewP2PClient( QSocket* pSocket );
    void slotGotREQCNEW(const QStringList &slCommand );
    void slotGotREQCRES(const QStringList &slCommand );
    void slotP2PNewSocket( QSocket *pSocket );

    /*! FR 전송 시도 */
    void slotTryREFR( const QString & sP2PCookie );

    void slotGotREFR( const QStringList &slCommand );
    void slotGotFR( const QStringList &slCommand );
    void slotSendREQCFR( const QString & sCommand );
    
signals:
	void ChangeGroupList ( QStringList & );
	void ChangeNickName ( QString sNick );
	void addNewGroup ( Group * );
	void updateMemoCount( int );
	void cySyncAuthError( bool );
	void cySyncCanceled();
	void changeStatus( int );
	void buddyChangeNick();
};
#endif   // _KNATEON_H_
