#include "stdafx.h"
#include "DownloadManager.h"

#include <qfileinfo>
#include <QApplication>


DownloadManager::DownloadManager()
{
	outBuf = NULL;
	mode = Mode_None;

	connect(&manager, SIGNAL(finished(QNetworkReply*)),
			SLOT(downloadFinished(QNetworkReply*)));
}

void DownloadManager::downloadToBuf(const QUrl &url, QByteArray* buf)
{
	outBuf = buf;
	outFilepath = "";
	mode = Mode_ToBuffer;
	state = Downloading;

	QNetworkRequest request(url);
	QNetworkReply *reply = manager.get(request);
}

void DownloadManager::downloadToFile(const QUrl &url)
{
	downloadToFile(url, saveFileName(url));
}

void DownloadManager::downloadToFile(const QUrl &url, const QString &filepath)
{
	outBuf = NULL;
	outFilepath = filepath;
	mode = Mode_ToFile;
	state = Downloading;

	QNetworkRequest request(url);
	QNetworkReply *reply = manager.get(request);
}

QString DownloadManager::saveFileName(const QUrl &url)
{
	QString path = url.path();
	QString basename = QFileInfo(path).fileName();

	if (basename.isEmpty())
		basename = "download";

	if (QFile::exists(basename))
	{
		int i = 0;
		basename += '.';
		while (QFile::exists(basename + QString::number(i)))
			++i;

		basename += QString::number(i);
	}

	return basename;
}

bool DownloadManager::saveToDisk(const QString &filename, QIODevice *data)
{
	QFile file(filename);
	if (!file.open(QIODevice::WriteOnly))
		return false;

	file.write(data->readAll());
	file.close();
	return true;
}

void DownloadManager::downloadFinished(QNetworkReply *reply)
{
	if (procResut(reply))
		state = DownlaodSuc;
	else
		state = DownloadFail;

	reply->deleteLater();
}

bool DownloadManager::procResut(QNetworkReply *reply)
{
	if (reply->error())
		return false;

	if (mode == Mode_ToBuffer)
	{
		(*outBuf) = reply->readAll();
	}
	else if (mode == Mode_ToFile)
	{
		QUrl url = reply->url();
		if (saveToDisk(outFilepath, reply))
			return false;
	}

	return true;
}

DownloadManager::State DownloadManager::currentState(void) const
{
	return state;
}

void DownloadManager::WaitWhileDownloading(void)
{
	while(state == DownloadManager::Downloading)
	{
		QApplication::processEvents();
	}
}
