#include "downloader.h"
#include <QEventLoop>
#include <QApplication>
#include <QDebug>

Downloader::Downloader(QObject *parent) :QObject(parent), busy(false)
{
    connect(&m_WebCtrl, SIGNAL(finished(QNetworkReply*)), this, SLOT(onDownloadFinished(QNetworkReply*)));
}

Downloader::~Downloader() {
}

QUrl Downloader::getUrl()
{
    return url;
}

void Downloader::setUrl(const QUrl &_url)
{
    url = _url;
}

void Downloader::waitForDownloaded()
{
    QEventLoop loop;
    connect(this, &Downloader::downloadFinished, &loop, &QEventLoop::quit);
    loop.exec();
}

void Downloader::start()
{
    if (busy) {
        qDebug() << "Cannot download " << url << ", downloader is busy!";
        return;
    }
    qDebug() << "Starting download " << url;

    busy = true;
    QNetworkRequest request(url);
    m_CurrentReply = m_WebCtrl.get(request);
    m_CurrentReply->setReadBufferSize(download_speed_limit);
    connect(m_CurrentReply, &QNetworkReply::readyRead, this, &Downloader::onReadyRead);
    connect(m_CurrentReply, &QNetworkReply::downloadProgress, this, &Downloader::progressChanged);
}

void Downloader::updateDownloadSpeedLimit(int bytes_per_sec)
{
    download_speed_limit = bytes_per_sec;
    if (m_CurrentReply)
        m_CurrentReply->setReadBufferSize(bytes_per_sec);
}

void Downloader::stop()
{
    m_CurrentReply->abort();
    busy = false;
}

void Downloader::onDownloadFinished(QNetworkReply*) {
    if (m_CurrentReply)
        m_CurrentReply->deleteLater();

    busy = false;
    emit downloadFinished();
}

void Downloader::onReadyRead()
{
    QByteArray readdata = m_CurrentReply->readAll();
    if (targetFile && targetFile->isWritable())
        targetFile->write(readdata);
    if (targetBytearray)
        targetBytearray->append(readdata);
}