/*
 *
 *  Kepas - KDE Easy Publish and Share
 *
 *  Copyright (C) 2008  Tom Patzig <tpatzig@suse.de>
 *
 *  This file is part of kepas.
 *
 *  kepas 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.
 *
 *  kepas 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 kepas; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
*/

#include "sender.h"

Sender::Sender(QObject* parent,QString llhostname, QString hostname, int port, QString user) : m_llhostname(llhostname), m_hostname(hostname), m_user(user)
{


	 http = new QHttp(llhostname,port,this);
	 qDebug() << "Host: " << llhostname << ":" << port;
	 
	 m_parent = parent;
	 requestPut = 0;
	 requestPost = 0;
	 requestGet = 0;
	 progress = 0;
	
	 connect(http, SIGNAL(requestFinished(int,bool)),this, SLOT(slotRequestFinished(int, bool)));
}

Sender::~Sender()
{
	 qDebug() << "~SENDER!";
	 if (requestGet)
		 delete requestGet;
	 if (requestPost)
	 	delete requestPost;
	 if (requestPut)
		delete requestPut;
	 if (progress)
		 delete progress;

	 if (http->hasPendingRequests()) {
		 http->clearPendingRequests();
		 qDebug() << "requests cleared";
	 }

	 disconnect(http, 0, 0, 0);
	 http->abort();
	 http->close();

}


void Sender::initFileSender(QString filename, int count)
{
	 m_filename = filename;
	 m_count = count;
	 QFileInfo info(m_filename);

	 qDebug() << "initFileSender - user= " << m_user;

	 requestGet = new QHttpRequestHeader("GET", "/");
	 requestGet->setValue("Request","Send");
	 requestGet->setValue("UserName",m_user);
	 requestGet->setValue("Type","Files");
	 requestGet->setValue("Count", QString::number(count));
	 requestGet->setValue("Name",info.fileName());
	 requestGet->setValue("Size", QString::number(info.size()));
	 requestGet->setValue("Host",m_hostname);
}

void Sender::initClipSender()
{
	requestPut = new QHttpRequestHeader("PUT", "/");
	requestPut->setValue("Request","SendClip");
	requestPut->setValue("UserName",m_user);
	requestPut->setValue("Type","Clipboard");
	requestPut->setValue("Host",m_hostname);
}

void Sender::initNoteSender()
{
	requestPut = new QHttpRequestHeader("PUT", "/");
	requestPut->setValue("Request","SendNote");
	requestPut->setValue("UserName",m_user);
	requestPut->setValue("Type","KNote");
	requestPut->setValue("Host",m_hostname);
}

void Sender::sendFileRequest()
{
	 
	 connect(http, SIGNAL(responseHeaderReceived (const QHttpResponseHeader&)), this, SLOT(slotGetResponseReceived(const QHttpResponseHeader&)));
	
	 http->request(*requestGet);

}

void Sender::sendClipRequest(QString clip)
{
	 connect(http, SIGNAL(responseHeaderReceived (const QHttpResponseHeader&)), this, SLOT(slotPutResponseReceived(const QHttpResponseHeader&)));
	 
	 QByteArray data;
	 data.append(clip.toLatin1());
	 http->request(*requestPut, data);
}

void Sender::slotGetResponseReceived(const QHttpResponseHeader& resp)
{

	 disconnect(http, SIGNAL(responseHeaderReceived (const QHttpResponseHeader&)), this, SLOT(slotGetResponseReceived(const QHttpResponseHeader&)));

 	 qDebug() << "Response Status Code " << resp.statusCode();

	 if (resp.statusCode() == 200) {

	 	 QFileInfo info(m_filename); 
	 	 QString sessionId = resp.value("SessionID");
	 	 
	 	 requestPost = new QHttpRequestHeader("POST", "/");
	 	 requestPost->setValue("SessionID",sessionId);
	 	 requestPost->setValue("Request","Payload");
	 	 requestPost->setValue("Type","File");
	 	 requestPost->setValue("Count",QString::number(m_count));
	 	 requestPost->setValue("Name",info.fileName());
	 	 requestPost->setValue("RelativePath","");
		 requestPost->setContentLength(info.size());
	 	 requestPost->setValue("Host",m_hostname);

		 qDebug() << "FileSize: " << info.size();

	 	 file = new QFile(m_filename,this);
		 qDebug() << "http state bevore: " << http->state();
       		 http->request(*requestPost,file);
		 qDebug() << "http state after: " << http->state();

		 connect(http,SIGNAL(dataSendProgress(int,int)),this,SLOT(slotTransferProgress(int,int)));
		 progress = new QProgressDialog("Transfer...","cancel",0,100,0);
		 progress->show();
		 connect(progress,SIGNAL(canceled()),this,SLOT(slotTransferCanceled()));

	 	 connect(http, SIGNAL(responseHeaderReceived (const QHttpResponseHeader&)), this, SLOT(slotTransferFinished(const QHttpResponseHeader&)));
		 

	} else {

		KMessageBox::information(this,"The peer denied the filetransfer","File Transfer, denied");
		emit transferDenied();
	}

}

void Sender::slotTransferProgress(int done, int total)
{
	float prog = ((float) done / (float) total) * 100.0;
	progress->setValue(prog);
}

void Sender::slotTransferCanceled()
{
	disconnect(http,SIGNAL(dataSendProgress(int,int)),this,SLOT(slotTransferProgress(int,int)));
	delete progress;
	progress = 0;
//	http->abort();
}


void Sender::slotPutResponseReceived(const QHttpResponseHeader& resp)
{
	disconnect(http, SIGNAL(responseHeaderReceived (const QHttpResponseHeader&)), this, SLOT(slotPutResponseReceived(const QHttpResponseHeader&)));
	qDebug() << "clip entry succesfull send!";	
	if (resp.statusCode() == 200) {
		emit transferFinished();		
	} else {
		QErrorMessage errorMsg;
                errorMsg.showMessage("Failed to send Clipboard Entry");
//		http->abort();
	}
}


void Sender::slotRequestFinished(int id, bool error)
{
	qDebug() << "request finished";
	if (error) {
		QErrorMessage errorMsg;
		errorMsg.showMessage(http->errorString());
//		http->abort();
	}

}
	
void Sender::slotTransferFinished(const QHttpResponseHeader& resp)
{
	qDebug() << "http DONE! " << resp.statusCode();
	delete progress;
	progress = 0;
	if (resp.statusCode() == 200)

		emit transferFinished();
	else 
	   slotRequestFinished(0, true);
}

