#include <QApplication>
#include <QQmlApplicationEngine>

#include <QLocale>
#include <QTranslator>
#include <QFontDatabase>

#include "CanController.h"

int main(int argc, char *argv[])
{
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
#endif
    QApplication app(argc, argv);

    QCoreApplication::setOrganizationName("Vku");
    QCoreApplication::setOrganizationDomain("Vku.rus");
    QCoreApplication::setApplicationName("Vku monitor");

    QFontDatabase::addApplicationFont(":/fonts/Roboto/Roboto-Black.ttf");
    QFontDatabase::addApplicationFont(":/fonts/Roboto/Roboto-BlackItalic.ttf");
    QFontDatabase::addApplicationFont(":/fonts/Roboto/Roboto-Bold.ttf");
    QFontDatabase::addApplicationFont(":/fonts/Roboto/Roboto-BoldItalic.ttf");
    QFontDatabase::addApplicationFont(":/fonts/Roboto/Roboto-Italic.ttf");
    QFontDatabase::addApplicationFont(":/fonts/Roboto/Roboto-Light.ttf");
    QFontDatabase::addApplicationFont(":/fonts/Roboto/Roboto-LightItalic.ttf");
    QFontDatabase::addApplicationFont(":/fonts/Roboto/Roboto-Medium.ttf");
    QFontDatabase::addApplicationFont(":/fonts/Roboto/Roboto-MediumItalic.ttf");
    QFontDatabase::addApplicationFont(":/fonts/Roboto/Roboto-Regular.ttf");
    QFontDatabase::addApplicationFont(":/fonts/Roboto/Roboto-Thin.ttf");
    QFontDatabase::addApplicationFont(":/fonts/Roboto/Roboto-ThinItalic.ttf");

    // QTranslator translator;
    // const QStringList uiLanguages = QLocale::system().uiLanguages();
    // for (const QString &locale : uiLanguages)
    // {
    //     const QString baseName = "VkuMonitor_" + QLocale(locale).name();
    //     if (translator.load(":/i18n/" + baseName))
    //     {
    //         app.installTranslator(&translator);
    //         break;
    //     }
    // }

    QTranslator translator;
    if (translator.load(":/i18n/VkuMonitor_ru_RU"))
    {
        app.installTranslator(&translator);
    }

    QQmlApplicationEngine engine;

    qmlRegisterSingletonType<CanController>("Vku", 1, 0, "CanController", &CanController::qmlInstance);

    const QUrl url(QStringLiteral("qrc:/main.qml"));
    QObject::connect(
        &engine,
        &QQmlApplicationEngine::objectCreated,
        &app,
        [url](QObject *obj, const QUrl &objUrl) {
            if (!obj && url == objUrl)
                QCoreApplication::exit(-1);
        },
        Qt::QueuedConnection);

    engine.addImportPath("qrc:/");
    engine.load(url);

    return app.exec();
}
