#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>

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

#include "DataController.h"

#ifdef _WIN32
#include "Windows.h"
#endif

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

    // qputenv("QT_SCALE_FACTOR", "0.5");

#ifdef _WIN32
    if (AttachConsole(ATTACH_PARENT_PROCESS)) {
        freopen("CONOUT$", "w", stdout);
        freopen("CONOUT$", "w", stderr);
    }
#endif

    QGuiApplication app(argc, argv);

    QCoreApplication::setOrganizationName("Tksi");
    QCoreApplication::setOrganizationDomain("Tksi.rus");
    QCoreApplication::setApplicationName("Tksi 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 auto uiLanguages = QLocale::system().uiLanguages();
    for (const auto& locale : uiLanguages)
    {
        const auto baseName = "TksiMonitor_" + QLocale(locale).name();
        if (translator.load(":/i18n/" + baseName))
        {
            app.installTranslator(&translator);
            break;
        }
    }

    QQmlApplicationEngine engine;

    qmlRegisterSingletonType<DataController>("Tksi", 1, 0, "DataController", &DataController::qmlInstance);

    auto isDebug = false;
#ifdef QT_DEBUG
    isDebug = true;
#endif
    engine.rootContext()->setContextProperty("isDebug", isDebug);

    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(QStringLiteral("qrc:/"));
    engine.load(url);

    return app.exec();
}
