/**********************************************************************************************
    Copyright (C) 2009 Oliver Eichler oliver.eichler@gmx.de

    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.

    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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA

**********************************************************************************************/

#include "CTransferAgent.h"
#include "CCanvas.h"

#include <QtGui>
#include <QtNetwork>

#define PORT 45454

CTransferAgent::CTransferAgent(QObject * parent)
: QObject(parent)
{
    detectSocket = new QUdpSocket(this);
    detectSocket->bind(PORT, QUdpSocket::ShareAddress);

    connect(detectSocket, SIGNAL(readyRead()), this, SLOT(answerRemoteControl()));

}


CTransferAgent::~CTransferAgent()
{
}


void CTransferAgent::answerRemoteControl()
{
    while (detectSocket->hasPendingDatagrams()) {
        QByteArray datagram;
        QHostAddress gtAddress;
        quint16 gtPort;

        datagram.resize(detectSocket->pendingDatagramSize());
        detectSocket->readDatagram(datagram.data(), datagram.size(), &gtAddress, &gtPort);
        QHostInfo qlmHost = QHostInfo::fromName( QHostInfo::localHostName() );
        //qDebug() << "Data read : " << datagram << " \r\n";
        if (datagram == "GETADRESS") {
            // SendBack to GT the QLM port and adress to connect for data synchronization
            qDebug() << "sendback hostname: " << qlmHost.hostName() << " address : " << gtAddress  << " port : " << gtPort << "\r\n";
            detectSocket->writeDatagram(qlmHost.hostName().toLocal8Bit(), qlmHost.hostName().size(), gtAddress, 45453);
        }
        else if (datagram == "START" && tcpServer.isNull()) {
            if(!tcpServer){
                emit syncStarted();
                tcpServer = new QTcpServer(this);
            }
            if (!tcpServer->listen(QHostAddress::Any, PORT)) {
                return;
            }
            connect(tcpServer, SIGNAL(newConnection()), this, SLOT(dataControl()));
            datagram = "ACK_START";
            detectSocket->writeDatagram( datagram.data(), datagram.size(), gtAddress, 45453);

            qDebug() << "listening for 10sec. to port" << PORT;
        }
        else if (datagram == "STOP" && !tcpServer.isNull()) {
	    delete tcpServer;
            datagram = "ACK_STOP";
            detectSocket->writeDatagram( datagram.data(), datagram.size(), gtAddress, 45453);
            emit syncStopped();
        }
    }
}


void CTransferAgent::dataControl()
{
    QTcpSocket *client = tcpServer->nextPendingConnection();
    connect(client, SIGNAL(disconnected()),client, SLOT(deleteLater()));
    protocol = new CProtocol(client);
    connect(protocol, SIGNAL(sigStatus(const QString&)), &CCanvas::self().getDlgTransfer(), SLOT(update(const QString&)));
    connect(protocol, SIGNAL(sigType(int)), &CCanvas::self().getDlgTransfer(), SLOT(mode(int)));

    CCanvas::self().getDlgTransfer().mode(-1);
    CCanvas::self().getDlgTransfer().update(tr("Start transfer..."));
}

