#include "downloadfile.h"
#include "tools.h"
#include <QMessageBox>

using namespace std;

// Initialization de la class
downloadFile::downloadFile()
{
}

//Slot activated when download is cancelled
void MainWindow::cancelled(QProcess * process)
{
	bool n = 0;

	info(DEBUGMACRO, "cancelled() => download cancelled: Terminating process");
	process->terminate();
	n = process->waitForFinished(30000);
	if (n == false)
	{
		info(DEBUGMACRO, "Process does not terminate after 30s, closing process");
		process->close();
	}
}

// launch a rsync processus downloading a file
void MainWindow::download()
{
	QString cmd;
	QStringList param;
	QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
	QString server = downloading.server;
	uint ipversion;

	info(DEBUGMACRO, "download() => launch a rsync processus to download a file");

	this->downloading.process = new QProcess(this);
	if (!this->downloading.user.isEmpty())
	{
		info(DEBUGMACRO, "Adding user to server (user@server");
		this->downloading.user = this->connexion.user;
		server = this->connexion.user + "@" + "[" + this->downloading.server + "]";
		env.insert("RSYNC_PASSWORD", this->downloading.password); // Add an environment variable
		this->downloading.process->setProcessEnvironment(env);
	}
	// Populating array with command and parameters for rsync
	cmd = "rsync";
	if (this->connexion.bandwidthLimit != 0)
	{
		info(DEBUGMACRO, "Adding download speed limit");
		param << "--bwlimit=" + QString::number(this->connexion.bandwidthLimit) + bwUnitChar[this->connexion.bandwidthLimitUnit];
	}

	ipversion = validateServer(&server);

	if (downloading.ipversion == 4 || downloading.ipversion == 6)
	{
		info(DEBUGMACRO, "Adding ip version parameter");
		param << "-" + QString::number(ipversion).trimmed();
	}

	param << "--port" << QString::number(this->downloading.port).trimmed();
	param << "-aXP";
	param << "[" + server + "]::" + this->downloading.service.trimmed() + "/" + preparePath(this->downloading.path) << preparePath(this->downloading.savePath) + "/";

	info(DEBUGMACRO, cmd + " " + param.join(" "));

	this->downloading.process->start(cmd, param);

	connect(this->downloading.process, SIGNAL(finished(int,QProcess::ExitStatus)), this, SLOT(downloadFinished(int, QProcess::ExitStatus)));
	//connect(this->downloading.process, SIGNAL(errorOccurred(QProcess::ProcessError error)), this, SLOT(downloadProcessError(QProcess::ProcessError error)));
	//connect(this->downloading.process, SIGNAL(readyReadStandardError()), this, SLOT(downloadProcessStderr()));
	connect(this->downloading.process, SIGNAL(readyReadStandardOutput()), this, SLOT(readRsyncOutput()));
}

void MainWindow::readRsyncOutput()
{
	QString line;
	int value;
	int pos;
	static QString dlSpeed;
	QStringList list;
	static QString filename;
	int i;
	int listSize;

	info(DEBUGMACRO, "readRsyncOutput()");
	while(1)
	{
		list.clear();
		line = QString::fromUtf8(this->downloading.process->readLine());
		info(DEBUGMACRO, "downloading progress : " + line);
		if (line.isEmpty())
		{
			break;
		}else
		{
			pos = line.indexOf("%");
			if (pos != -1)
			{
				line = line.simplified();
				list = line.split(" ");
				listSize = list.count() / 4;
				for (i = 0; i < listSize; i++)
				{
					value = list.at(i *4 + 1).chopped(1).toInt();
					dlSpeed = list.at(i * 4 + 2);

						// sending progress to Main window
					info (DEBUGMACRO, "sending progress to Main window");
					emit progressSignal(value);
					emit fileName(filename + "   %p%" + "\t " + dlSpeed);
				}
			}else
			{
				if (!line.contains("receiving"))
				{
					filename = line.remove(QChar('\n'), Qt::CaseInsensitive);
					emit fileName(filename + "   %p%\t " + dlSpeed);
				}
			}
		}
	}
}
