#include "videospatch.h"
#include "LotroDat/LotroDat.h"
#include "LotroDat/Database.h"

#include <QUrlQuery>
#include <QSet>
#include <QThread>

VideosPatch::VideosPatch(LotroDatManager *mgr, QObject *parent) : Patch("VideosPatch", mgr, parent)
{
}

void VideosPatch::checkForUpdates()
{
    QUrlQuery query; // query for building GET-request aka patch-version

    foreach (QString db_name, databases_names) {
        query.addQueryItem(db_name, "100");
    }

    QUrl target_url;
    target_url.setUrl(Settings::getValue("Network/patch_updates_url").toString());
    target_url.setQuery(query);

    QByteArray target_array;
    Downloader downloader;
    downloader.setUrl(target_url);
    downloader.targetBytearray = &target_array;
    downloader.start();
    downloader.waitForDownloaded();

    if (target_array.isEmpty()) {
        qWarning() << *this << "Cannot check for updates, target_array is empty!";
        emit errorOccured(E_CHECKFORUPDATES, this, "");
        emit operationFinished(E_CHECKFORUPDATES, this);
        return;
    }

    QStringList patch_info = QString(target_array).split('|');
    if (patch_info.size() != databases_names.size()) {
        qCritical() << __FUNCTION__ << "Incorrect patches number! Data: " << patch_info;
        emit errorOccured(E_CHECKFORUPDATES, this, "");
        emit operationFinished(E_CHECKFORUPDATES, this);
        return;
    }

    for (int i = 0; i < databases_names.size(); ++i) {
        QStringList patch_data = patch_info[i].split(":::");
        if (patch_data.size() != 3) {
            qCritical() << __FUNCTION__ << "Incorrect patch entry size! Entry: " << patch_data;
            emit errorOccured(E_CHECKFORUPDATES, this, "");
            emit operationFinished(E_CHECKFORUPDATES, this);
            return;
        }

        QString patch_filename = Settings::getValue("General/PatchDownloadDir").toString() + "/" + QUrl(patch_data[0]).fileName();

        Settings::setValue("PatchDatabases/" + databases_names[i] + "/url", patch_data[0]);
        Settings::setValue("PatchDatabases/" + databases_names[i] + "/hashsum", patch_data[1]);
        Settings::setValue("PatchDatabases/" + databases_names[i] + "/datetime", patch_data[2]);
        Settings::setValue("PatchDatabases/" + databases_names[i] + "/path", patch_filename);
    }

    emit operationFinished(E_CHECKFORUPDATES, this);
}

void VideosPatch::download()
{
    foreach (QString db_name, databases_names) {
        QString settings_prefix = "PatchDatabases/" + db_name;

        QString target_filename = QApplication::applicationDirPath() + "/" + Settings::getValue(settings_prefix + "/path").toString();
        qDebug() << patch_name_ << ": Checking if file " << target_filename << " matches its hashsum";

        if (FileSystem::fileHash(target_filename) == Settings::getValue(settings_prefix + "/hashsum").toString()) {
            qInfo() << *this << ": file " << target_filename << " is up-to-date, no need to download";
            continue;
        }

        FileSystem::createFilePath(target_filename);
        QFile* target_file = new QFile(target_filename);
        if (!target_file->open(QIODevice::ReadWrite | QIODevice::Truncate)) {
            qWarning() << *this << "Cannot open file " << target_filename;
            continue;
        }

        qInfo() << *this << ": beginning download of file " << target_filename;

        Downloader* downloader = new Downloader();
        downloader->setUrl(Settings::getValue(settings_prefix + "/url").toUrl());
        downloader->targetFile = target_file;
        connect(downloader, &Downloader::progressChanged, this, &VideosPatch::onDownloaderProgressChanged);
        connect(downloader, &Downloader::downloadFinished, this, &VideosPatch::onDownloaderFinished);
        downloaders_.insert(downloader);
        downloader->start();
    }

    if (downloaders_.empty()) {
        emit operationFinished(E_DOWNLOAD, this);
    }
}

void VideosPatch::install()
{
    QThread::msleep(500);
    emit operationFinished(E_INSTALL, this);
}

void VideosPatch::activate()
{
    QThread::msleep(500);
    emit operationFinished(E_ACTIVATE, this);
}

void VideosPatch::onDownloaderProgressChanged(Downloader *, Downloader::Status)
{
    Downloader::Status all_downloads_status;
    foreach (Downloader* downloader, downloaders_) {
        all_downloads_status = all_downloads_status + downloader->getDownloadStatus();
    }

    emit progressChanged(OperationProgress(all_downloads_status), this);
}

void VideosPatch::onDownloaderFinished(Downloader *ptr)
{
    ptr->targetFile->close();
    ptr->targetFile->deleteLater();

    Downloader::Status all_downloads_status;
    for (const Downloader* downloader : downloaders_) {
        all_downloads_status = all_downloads_status + downloader->getDownloadStatus();
    }

    if (!all_downloads_status.running) {
        for (Downloader* downloader : downloaders_) {
            downloader->deleteLater();
        }
        downloaders_.clear();
        emit operationFinished(E_DOWNLOAD, this);
    }
}
