#include "graphicspatch.h"
#include "LotroDat/LotroDat.h"
#include "LotroDat/Database.h"
#include "models/lotrodatmanager.h"

#include <QUrlQuery>
#include <QSet>

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

void GraphicsPatch::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 GraphicsPatch::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, &GraphicsPatch::onDownloaderProgressChanged);
        connect(downloader, &Downloader::downloadFinished, this, &GraphicsPatch::onDownloaderFinished);
        downloaders_.insert(downloader);
        downloader->start();
    }

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

void GraphicsPatch::install()
{
    installLoadscreens();

    foreach (QString db_name, QStringList({"image", "texture"})) {
        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 GraphicsPatch::activate()
{
    emit operationFinished(E_ACTIVATE, this);
    return;

    if (Settings::getValue("Components/loadscreens").toBool()) {
        enableLoadscreens();
    } else {
        disableLoadscreens();
    }

    QString operation_name;

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

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

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

    is_being_patched_by_lotro_dat_manager_ = true;
}

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

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

void GraphicsPatch::installLoadscreens()
{
    if (!Settings::getValue("DatabaseNeedInstall/loadscreen").toBool()) {
        return;
    }

    QString locale_prefix = Settings::getValue("Lotro/original_locale").toString();

    const QStringList loadscreens_filenames = {
        locale_prefix == "English" ? "lotro_ad_pregame.jpg" : "lotro_ad_pregame_" + locale_prefix + ".jpg",
        "lotro_generic_teleport_screen_01.jpg",
        "lotro_generic_teleport_screen_02.jpg",
        "lotro_generic_teleport_screen_03.jpg",
        "lotro_generic_teleport_screen_04.jpg",
        "lotro_generic_teleport_screen_05.jpg",
        "lotro_generic_teleport_screen_06.jpg",
        "lotro_generic_teleport_screen_07.jpg",
        "lotro_generic_teleport_screen_08.jpg",
        "lotro_generic_teleport_screen_09.jpg",
        "lotro_generic_teleport_screen_10.jpg"
    };

    OperationProgress progress;
    progress.install_finished_parts = 0;
    progress.install_total_parts = loadscreens_filenames.size() * 2;

    LOTRO_DAT::Database database;
    if (!database.InitDatabase(Settings::getValue("PatchDatabases/Loadscreen/path").toString().toStdString())) {
        qCritical() << *this << "database.InitDatabase() of " << Settings::getValue("PatchDatabases/Loadscreen/path").toString() << " FAILED!";
        return;
    }

    LOTRO_DAT::SubfileData data;

    QString logo_path = Settings::getValue("Lotro/game_path").toString() + "/raw/" + (locale_prefix == "English" ? "en" : locale_prefix) + "/logo/";

    for (size_t i = 0; i < qMin(size_t(loadscreens_filenames.size()), database.CountRows()); ++i) {
        data = database.GetNextFile();
        QFile::remove(logo_path + loadscreens_filenames[i] + "_ru");

        if (!data.binary_data.WriteToFile((logo_path + loadscreens_filenames[i] + "_ru").toLocal8Bit())) {
            qWarning() << patch_name_ << "Cannot write to file " << logo_path + loadscreens_filenames[i];
        }

        progress.install_finished_parts++;
        emit progressChanged(progress, this);
    }

    for (int i = 0; i < loadscreens_filenames.size(); ++i) {
        QFile::copy(logo_path + loadscreens_filenames[i], logo_path + loadscreens_filenames[i] + "_orig"); // Will not copy if _orig file already exists
        progress.install_finished_parts++;
        emit progressChanged(progress, this);
    }

    Settings::setValue("DatabaseNeedInstall/loadscreen", false);
}

void GraphicsPatch::enableLoadscreens()
{
    QString locale_prefix = Settings::getValue("Lotro/original_locale").toString();
    QString logo_path = Settings::getValue("Lotro/game_path").toString() + "/raw/" + (locale_prefix == "English" ? "en" : locale_prefix) + "/logo/";

    const QStringList loadscreens_filenames = {
        locale_prefix == "English" ? "lotro_ad_pregame.jpg" : "lotro_ad_pregame_" + locale_prefix + ".jpg",
        "lotro_generic_teleport_screen_01.jpg",
        "lotro_generic_teleport_screen_02.jpg",
        "lotro_generic_teleport_screen_03.jpg",
        "lotro_generic_teleport_screen_04.jpg",
        "lotro_generic_teleport_screen_05.jpg",
        "lotro_generic_teleport_screen_06.jpg",
        "lotro_generic_teleport_screen_07.jpg",
        "lotro_generic_teleport_screen_08.jpg",
        "lotro_generic_teleport_screen_09.jpg",
        "lotro_generic_teleport_screen_10.jpg"
    };

    OperationProgress progress;
    progress.install_total_parts = loadscreens_filenames.size();

    for (int i = 0; i < loadscreens_filenames.size(); ++i) {
        QFile::remove(logo_path + loadscreens_filenames[i]);
        QFile::copy(logo_path + loadscreens_filenames[i] + "_ru", logo_path + loadscreens_filenames[i]);

        progress.install_finished_parts++;
        emit progressChanged(progress, this);
    }
}

void GraphicsPatch::disableLoadscreens()
{
    QString locale_prefix = Settings::getValue("Lotro/original_locale").toString();
    QString logo_path = Settings::getValue("Lotro/game_path").toString() + "/raw/" + (locale_prefix == "English" ? "en" : locale_prefix) + "/logo/";

    const QStringList loadscreens_filenames = {
        locale_prefix == "English" ? "lotro_ad_pregame.jpg" : "lotro_ad_pregame_" + locale_prefix + ".jpg",
        "lotro_generic_teleport_screen_01.jpg",
        "lotro_generic_teleport_screen_02.jpg",
        "lotro_generic_teleport_screen_03.jpg",
        "lotro_generic_teleport_screen_04.jpg",
        "lotro_generic_teleport_screen_05.jpg",
        "lotro_generic_teleport_screen_06.jpg",
        "lotro_generic_teleport_screen_07.jpg",
        "lotro_generic_teleport_screen_08.jpg",
        "lotro_generic_teleport_screen_09.jpg",
        "lotro_generic_teleport_screen_10.jpg"
    };

    OperationProgress progress;
    progress.install_total_parts = loadscreens_filenames.size();

    for (int i = 0; i < loadscreens_filenames.size(); ++i) {
        QFile::remove(logo_path + loadscreens_filenames[i]);
        QFile::copy(logo_path + loadscreens_filenames[i] + "_orig", logo_path + loadscreens_filenames[i]);

        progress.install_finished_parts++;
        emit progressChanged(progress, this);
    }
}
