#include "legacyapplication.h"

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

void logMessageHandler(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
    QString message_type;

    switch (type) {
    case QtDebugMsg:
        message_type = "[DEBG]";
        break;
    case QtInfoMsg:
        message_type = "[INFO]";
        break;
    case QtWarningMsg:
        message_type = "[WARN]";
        break;
    case QtCriticalMsg:
        message_type = "[CRIT]";
        break;
    case QtFatalMsg:
        message_type = "[FATL]";
        break;
    default:
        message_type = "[UNKN]";
        break;
    }

    QString filename = context.category;
    QString function = context.function;
    QString line_number = QString::number(context.line);

    QString s = QString("%1: %2\n")
                .arg(message_type)
                .arg(msg);

    QFile log_file("legacy_v2.log");
    log_file.open(QIODevice::ReadWrite | QIODevice::Append);
    QTextStream stream(&log_file);
    stream << s;
    log_file.close();
    fprintf(stderr, "%s", qUtf8Printable(s));
    fflush(stderr);
}

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

bool LegacyApplication::init()
{
    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";

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

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