/*
    SPDX-License-Identifier: LGPL-2.1-or-later OR MIT
    SPDX-FileCopyrightText: 2021-2026 Andreas Cord-Landwehr <cordlandwehr@kde.org>
*/

#include "browserapplication.h"
#include "filtercriteriamodel.h"
#include "kjournald_version.h"
#include <KAboutData>
#include <KCrash>
#include <KLocalizedQmlContext>
#include <KLocalizedString>
#include <KSandbox>
#include <QApplication>
#include <QCommandLineParser>
#include <QDebug>
#include <QDir>
#include <QIcon>
#include <QQmlApplicationEngine>
#include <QQuickStyle>
#include <QtQml/QQmlExtensionPlugin>

Q_IMPORT_PLUGIN(org_kde_kjournaldbrowserPlugin)

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    QGuiApplication::setWindowIcon(QIcon::fromTheme(QStringLiteral("utilities-log-viewer")));
    app.setOrganizationName("KDE");

    KCrash::initialize();

    // use org.kde.desktop style unless another style is forced
    if (qEnvironmentVariableIsEmpty("QT_QUICK_CONTROLS_STYLE")) {
        QQuickStyle::setStyle(QStringLiteral("org.kde.desktop"));
    }

    KLocalizedString::setApplicationDomain("kjournald");
    static KAboutData aboutData(QStringLiteral("kjournald"),
                                i18nc("@title Displayed program name", "KJournald Browser"),
                                KJOURNALD_VERSION_STRING,
                                i18nc("@title KAboutData: short program description", "Viewer for Journald logs"),
                                KAboutLicense::LGPL_V2_1,
                                i18nc("@info:credit", "(c) 2021-2026 The KJournald Developers"),
                                i18nc("@title Short program description", "Viewer for Journald databases, which are generated by the Journald logging tool."));
    aboutData.setProgramLogo(app.windowIcon());
    aboutData.addAuthor(i18nc("@info:credit Developer name", "Andreas Cord-Landwehr"),
                        i18nc("@info:credit Role", "Original Author"),
                        QStringLiteral("cordlandwehr@kde.org"));
    aboutData.setTranslator(i18nc("NAME OF TRANSLATORS", "Your names"), i18nc("EMAIL OF TRANSLATORS", "Your emails"));
    aboutData.setDesktopFileName(QStringLiteral("org.kde.kjournaldbrowser"));
    aboutData.setProductName("kjournald");
    aboutData.setBugAddress("submit@bugs.kde.org");
    KAboutData::setApplicationData(aboutData);

    FilterCriteriaModel filterCriteriaModel;
    {
        QSettings settings;
        if (settings.contains(BrowserApplication::ID_logPriority)) {
            filterCriteriaModel.setInitialPriorityFilter(settings.value(BrowserApplication::ID_logPriority).toInt());
        }
    }

    QCommandLineParser parser;
    parser.setApplicationDescription(i18n("Journald Log Viewer"));
    parser.addHelpOption();
    parser.addVersionOption();
    const QCommandLineOption pathOption("D", "Path to journald database folder", "path");
    parser.addOption(pathOption);
    parser.process(app);

    QString initialJournalPath;
    bool requestInitialJournalViaPortal{false}; // indicates if a desktop portal must be used to access location
    if (parser.isSet(pathOption)) {
        const bool sandboxed = KSandbox::isInside();
        QDir journalDir(parser.value(pathOption));
        if (journalDir.exists()) {
            qInfo() << "initial journal: setting path to" << journalDir.absolutePath();
            initialJournalPath = journalDir.absolutePath();
        } else if (sandboxed && !journalDir.exists()) {
            qInfo() << "initial journal: requesting portal for path not accessible in sandbox" << journalDir.absolutePath();
            requestInitialJournalViaPortal = true;
        } else {
            qWarning() << "initial journal: directory does not exist, skipping:" << journalDir.absolutePath();
        }
    }

    QQmlApplicationEngine engine;
    const QVariantMap initialProperties = {{"filterModel", QVariant::fromValue(&filterCriteriaModel)},
                                           {"initialJournalPath", initialJournalPath},
                                           {"initialJournalPathViaPortal", QVariant::fromValue(requestInitialJournalViaPortal)}};
    engine.setInitialProperties(initialProperties);
    KLocalization::setupLocalizedContext(&engine);
    QObject::connect(
        &engine,
        &QQmlApplicationEngine::objectCreationFailed,
        &app,
        [](const QUrl &url) {
            qCritical() << "Failed to create main QML component" << url;
            QCoreApplication::exit(-1);
        },
        Qt::QueuedConnection);
    engine.loadFromModule("org.kde.kjournaldbrowser", "Main");

    return app.exec();
}
