/***************************************************************************
 *   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 P2PSERVER_H
#define P2PSERVER_H

#include <stdlib.h>
#include <qptrdict.h>
#include <qstringlist.h>
#include <kextsock.h>
#include <qsocket.h>

#include "p2pconnection.h"
#include "../currentaccount.h"

class Client;
class NOMHTTPProxy;

class P2PSocket : public QSocket 
{
Q_OBJECT
public:
    P2PSocket( QObject * parent = 0, const char * name = 0 ) :
        QSocket( parent, name )
//         m_pSocketNotifier(0)
        {
            connect( this, SIGNAL( readyRead() ), this, SLOT( slotRead() ) );
        };
    
    
    ~P2PSocket()
        {
        };
    
    
    
//     void setSocketNotifier( QSocketNotifier *socketNotifier ) 
//         {
//             m_pSocketNotifier = socketNotifier;
//         }
//     void freeSocketNotifier()
//         {
//             if ( m_pSocketNotifier ) {
//                 m_pSocketNotifier->setEnabled( false );
//                 delete m_pSocketNotifier;
//                 m_pSocketNotifier = 0;
//             }
//         }
    
private slots:
    void slotRead() 
        {
            Q_ULONG nByte = bytesAvailable(); 
            char *str;
            str = (char *)malloc( nByte + 1 );
            memset( str, 0x00, nByte + 1 );
            readBlock ( str, nByte );

            kdDebug() << "GET_DATA : [" << str << "]" << endl;
            emit IncomingMessage("[ P2P_S ]-{" + QString( str ) + "}-");      

            if ( strncmp( str, "ATHC", 4) == 0 ) {
                disconnect( this, 0, 0, 0 );
                /*! ex) ATHC 0 [Sender ID] [Receiver ID] [DP Cookie] 6004 0 */

                kdDebug() << "Found ATHC!" << endl;
                QStringList slCommand = QStringList::split( " ", str );
                kdDebug() << "DP Cookie : " << slCommand[4] << endl;
        
                char sATHC100[] = "ATHC 0 100 6004 0\r\n";
                writeBlock( sATHC100, sizeof( sATHC100 ) - 1 );
                flush();
        
                emit OutgoingMessage("[ P2P_S ]-{" + QString( sATHC100 ) + "}-");      
                // emit gotServerATHC( socket, slCommand[4] );
                gotSocketDPCookie( socket(), slCommand[4] );
                // disconnect(socket, SIGNAL(readyRead()), this, SLOT(slotSocketRead()));
            }
        };
    
signals:
    void IncomingMessage( const QString & );
    void OutgoingMessage( const QString & );
    void gotSocketDPCookie( int nSocket, const QString & );
};

    

/**
   @author Doo-Hyun Jang <ring0320@nate.com>
*/
class P2PServer : public P2PConnection
{
Q_OBJECT
public:
    P2PServer(QObject *parent = 0, const char *name = 0);
    ~P2PServer();
    void startServer();
    void stopServer();

    int getPort() { return m_nPort; }
    void setPort( int nPort ) { m_nPort = nPort; }
    // void ConnectToFR(QString &sIP, int nPort, const QString & YourID, const QString & MyID, const QString &DPCookie, const QString &FRCookie);
    void setCurrentAccount(CurrentAccount* CurrentAccount) { pCurrentAccount=CurrentAccount; }

protected:
    ServerSocket* m_server;
    CurrentAccount* pCurrentAccount;
    QString m_sServer;
    int m_nPort;
	
private:
    QPtrList<P2PSocket> m_P2PSocketList;
	NOMHTTPProxy *m_pHttpProxy;

protected slots:
    void slotNewClient(QSocket* socket);
    void slotClientDisconnected();
    void slotSocketRead();
    void slotSocketReadFR();
    void slotSendATHCtoFR();
    void slotSendATHC();
    void slotConnectP2PFR( const QStringList& slCommand );
    void slotConnectToP2P(const QStringList& slCommand);
    // void slotP2PSocketError();
    void slotTimeOut(SendFileInfo* pSendFileInfo);
    void slotReceivedREFR( const QStringList& slCommand);
    void slotSendFRIN();

    void slotIncomingMessage( const QString & message );
    void slotOutgoingMessage( const QString & message );
    void slotGotSocketDPCookie( int socket, const QString & dpcookie );

signals:
    void connTimeOut( SendFileInfo* );
    void gotNewClient( QSocket* pSocket );
    
    void gotServerATHC( const QSocket* pSocket, const QString &sDPCooke );
    void gotSocketDPCookie( int socket, const QString &dpcookie );
};

#endif
