// SPDX-FileCopyrightText: 2025 UnionTech Software Technology Co., Ltd.
//
// SPDX-License-Identifier: GPL-3.0-or-later

#include "err_notifier_service.h"

#include <QCoreApplication>
#include <QDBusConnection>
#include <QLocale>
#include <QStandardPaths>
#include <QTranslator>

const QString PLUGIN_NAME = QStringLiteral("plugin-immutable-err-notifier");
static ErrNotifierService *g_service = nullptr;

static void loadTranslator(QObject *parent)
{
    QTranslator *translator = new QTranslator(parent);
    QString languagePath = QStandardPaths::locate(QStandardPaths::GenericDataLocation,
                                                  QString("deepin-immutable-eventd/translations"),
                                                  QStandardPaths::LocateDirectory);

    QString localeName = QLocale::system().name();
    bool translatorLoaded = translator->load(languagePath + "/" + PLUGIN_NAME + "_" + localeName);

    // Fallback: try language code without country (e.g., zh_CN -> zh)
    if (!translatorLoaded && localeName.contains('_')) {
        QString languageCode = localeName.split('_').first();
        translatorLoaded = translator->load(languagePath + "/" + PLUGIN_NAME + "_" + languageCode);
        if (translatorLoaded) {
            qInfo(lc_err_notifier) << "Loaded fallback translator for language:" << languageCode;
        }
    }

    if (!translatorLoaded) {
        qWarning(lc_err_notifier) << "Failed to load translator for locale:" << localeName;
    } else {
        qApp->installTranslator(translator);
    }
}

extern "C" int DSMRegister(const char *name, void *data)
{
    (void)name;

    if (!data) {
        return -1;
    }

    auto *connection = reinterpret_cast<QDBusConnection *>(data);
    if (!connection) {
        return -1;
    }

    if (g_service) {
        return 0;
    }

    g_service = new ErrNotifierService(*connection);
    if (!g_service->initialize()) {
        delete g_service;
        g_service = nullptr;
        return -1;
    }

    loadTranslator(g_service);

    return 0;
}

extern "C" int DSMUnRegister(const char *name, void *data)
{
    (void)name;
    (void)data;

    if (g_service) {
        delete g_service;
        g_service = nullptr;
    }

    return 0;
}
