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

#include <QCoreApplication>
#include <qfileinfo>


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)
{
	procResut(reply);

	reply->deleteLater();
}

void DownloadManager::procResut(QNetworkReply *reply)
{
	if (reply->error())
	{
		state = DownloadFail;
		return;
	}

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

	state = DownlaodSuc;
}

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