#include "legacyapplication.h"
#include "models/lotrodatmanager.h"
#include "models/patchlist.h"
#include "widgets/mainwindow.h"

#include <QLockFile>
#include <QMessageBox>
#include <QResource>
#include <QFontDatabase>
#include <QMessageLogContext>

#include "utils.h"

extern Q_CORE_EXPORT int qt_ntfs_permission_lookup;


LegacyApplication::LegacyApplication() {
    qInstallMessageHandler(logMessageHandler);

    modules_init_timer_.setInterval(1 * 1000); // one second.
    connect(&modules_init_timer_, &QTimer::timeout, this, &LegacyApplication::InitModules);
    modules_init_timer_.stop();
}

bool LegacyApplication::init()
{
    qt_ntfs_permission_lookup++;
    qDebug() << "Starting initialisation...";

    QCoreApplication::setOrganizationName("LotroLegacy");
    QCoreApplication::setOrganizationDomain("translate.lotros.ru");
    QCoreApplication::setApplicationName("Legacy_v2");

    QSettings::setDefaultFormat(QSettings::IniFormat);
    QSettings::setPath(QSettings::IniFormat, QSettings::UserScope, QApplication::applicationDirPath());
    QSettings::setPath(QSettings::IniFormat, QSettings::SystemScope, QApplication::applicationDirPath());

    qDebug() << "Checking if there's another instance of Legacy";
    if (!checkSingleAppInstance()) {
        return false;
    }

    qDebug() << "Initialising fonts and resources";
    QDir::setCurrent(QApplication::applicationDirPath());
    if (!FileSystem::folderExists("backup")) {
        QDir dir;
        dir.mkdir("backup");
    }

    QResource::registerResource(QApplication::applicationDirPath() + "/data01.gtr");
    QResource::registerResource(QApplication::applicationDirPath() + "/data02.gtr");

    QFontDatabase::addApplicationFont(":/fonts/trpro.ttf");
    QFontDatabase::addApplicationFont(":/fonts/CrimsonText.ttf");
    QFontDatabase::addApplicationFont(":/fonts/EBGaramond.ttf");
    QFontDatabase::addApplicationFont(":/fonts/aniron.ttf");

    qDebug() << "Starting Lotro Manager initialization...";

    lotro_dat_manager = new LotroDatManager();
    lotro_dat_manager_thread = new QThread();
    connect(lotro_dat_manager_thread, &QThread::finished, lotro_dat_manager, &LotroDatManager::deleteLater);
    lotro_dat_manager->moveToThread(lotro_dat_manager_thread);
    lotro_dat_manager_thread->start();

    qDebug() << "Starting Patch list initialisation...";

    patch_list = new PatchList(lotro_dat_manager);

    qDebug() << "Starting GUI initialisation...";

    gui = new MainWindow(patch_list);
    connect(this, &LegacyApplication::ErrorStatusChanged, gui, &MainWindow::onErrorStatusChanged);
    connect(this, &LegacyApplication::SecondsToNextTryToInitChanged, gui, &MainWindow::onSecondsToNextTryToInitChanged);

    qDebug() << "Starting functional modules initialisation...";

    InitModules();
    return true;
}


void LegacyApplication::InitModules()
{
    if (seconds_after_previous_try_to_init_ + 1 < try_to_init_timeout_) {
        seconds_after_previous_try_to_init_++;
        emit SecondsToNextTryToInitChanged(try_to_init_timeout_ - seconds_after_previous_try_to_init_);
        return;
    }

    modules_init_timer_.stop();
    seconds_after_previous_try_to_init_ = 0;
    AppErrorStatus status = CheckAppPrerequesities();
    emit ErrorStatusChanged(status);

    if (status == E_NO_ERRORS) {
        patch_list->initialize();
        patch_list->startAutoUpdate();
    } else {
        qWarning() << "LegacyApplication: Couldnt init functional modules!";
        modules_init_timer_.start();
    }
}
