#include "legacyapplication.h"

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

LegacyApplication::LegacyApplication(int &argc, char **argv)
    : QApplication(argc, argv)
    , lotro_dat_manager(nullptr)
    , lotro_dat_manager_thread(nullptr)
    , patch_list(nullptr)
    , gui(nullptr)
{
}

bool LegacyApplication::init()
{
    qDebug() << __func__ << "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() << __func__ << "Checking if there's another instance of Legacy";

    QLockFile lockFile(QDir::temp().absoluteFilePath("rulotro.lock"));
    if(!lockFile.tryLock(1)){
        qDebug() << __func__ << "Lock file already exists! Some other application is already running...";
        QMessageBox msgBox;
        msgBox.setIcon(QMessageBox::Warning);
        msgBox.setText("Приложение уже запущено.\nРазрешено запускать только один экземпляр приложения.");
        msgBox.exec();
        return false;
    }

    qDebug() << __func__ << "Initialising fonts and resources";

    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() << __func__ << "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() << __func__ << "Starting Patch list initialisation...";

    patch_list = new PatchList(lotro_dat_manager);

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

    gui = new MainWindow(patch_list);
    qDebug() << __func__ << "Legacy Initialization finished!";

    patch_list->startAutoUpdate();
    patch_list->initialize();
    return true;
}
