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

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

NetworkDownloader::~NetworkDownloader() {
}

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

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

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

void NetworkDownloader::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, &NetworkDownloader::onReadyRead);
    connect(m_CurrentReply, &QNetworkReply::downloadProgress, this, &NetworkDownloader::progressChanged);
}

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

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

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

    busy = false;
    emit downloadFinished();
}

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