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

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

SoundsPatch::SoundsPatch(LotroDatManager *mgr, QObject *parent) : Patch("SoundsPatch", mgr, parent)
{
    connect(lotro_mgr_, &LotroDatManager::operationStarted, this, &SoundsPatch::onLotroDatManagerOperationStarted);
    connect(lotro_mgr_, &LotroDatManager::operationFinished, this, &SoundsPatch::onLotroDatManagerOperationFinished);
    connect(lotro_mgr_, &LotroDatManager::statusChanged, this, &SoundsPatch::onLotroDatManagerStatusChanged);
}

void SoundsPatch::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 SoundsPatch::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;

        Settings::setValue("DatabaseNeedInstall/" + db_name, true);

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

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

void SoundsPatch::install()
{
    foreach (QString db_name, QStringList({"sound"})) {
        if (!Settings::getValue("DatabaseNeedInstall/" + db_name).toBool()) {
            continue;
        }

        ++elapsed_patches_to_install_;
        QMetaObject::invokeMethod(lotro_mgr_, "installPatch", Qt::QueuedConnection,
                                  Q_ARG(QString, getPatchName() + "_" + db_name),
                                  Q_ARG(QString, Settings::getValue("PatchDatabases/" + db_name + "/path").toString())
                                  );
    }

    if (elapsed_patches_to_install_ == 0) {
        emit operationFinished(E_INSTALL, this);
    }
}

void SoundsPatch::activate()
{
    emit operationFinished(E_ACTIVATE, this);
    return;

    QString operation_name = Settings::getValue("Components/sounds").toBool() ? "enableCategory" : "disableCategory";
    ++elapsed_patches_to_install_;
    QMetaObject::invokeMethod(lotro_mgr_, operation_name.toLocal8Bit().constData(), Qt::QueuedConnection,
                              Q_ARG(QString, getPatchName() + "_sounds"),
                              Q_ARG(LotroDatManager::Category, LotroDatManager::Category::E_AUDIOS_COMMON)
                              );
}

void SoundsPatch::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 SoundsPatch::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);
    }
}

void SoundsPatch::onLotroDatManagerOperationFinished(QString operation_name, QVector<QVariant> args, bool successful)
{
    if (args.size() == 0 || !args[0].toString().contains(getPatchName())) {
        return; // This means, that message from LotroManager is addressed to another patchset
    }

    if (operation_name.contains("installPatch")) {
        if (!successful) {
            qCritical() << *this << "Database " + args[0].toString() + " (" + args[1].toString() + ") was not installed due to Legacy core error.";
            emit errorOccured(E_INSTALL, this, "Database " + args[0].toString() + " (" + args[1].toString() + ") was not installed due to Legacy core error.");
        }
        QString db_name = args[0].toString().split('_').at(1);
        Settings::setValue("DatabaseNeedInstall/" + db_name, false);

        --elapsed_patches_to_install_;
        if (!elapsed_patches_to_install_) {
            is_being_patched_by_lotro_dat_manager_ = false;
            emit operationFinished(E_INSTALL, this);
        }
    }

    if (operation_name.contains("enableCategory") || operation_name.contains("disableCategory")) {
        if (!successful) {
            qCritical() << *this << "Error in patch " + args[0].toString() + ": activating category " + QString::number(args[1].toInt()) + " failed.";
            emit errorOccured(E_ACTIVATE, this, "Error in patch " + args[0].toString() + ": activating category " + QString::number(args[1].toInt()) + " failed.");
        }

        --elapsed_patches_to_install_;
        if (!elapsed_patches_to_install_) {
            is_being_patched_by_lotro_dat_manager_ = false;
            emit operationFinished(E_ACTIVATE, this);
        }
    }
}

void SoundsPatch::onLotroDatManagerOperationStarted(QString, QVector<QVariant> args)
{
    if (args.size() == 0 || !args[0].toString().contains(getPatchName())) {
        return;
    }

    is_being_patched_by_lotro_dat_manager_ = true;
}

void SoundsPatch::onLotroDatManagerStatusChanged(LotroDatManager::Status status)
{
    if (!is_being_patched_by_lotro_dat_manager_) {
        return;
    }

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