#include <QApplication>
#include <QMainWindow>
#include <QIcon>
#include <QTranslator>
#include <QLocale>
#include <QCoreApplication>
#include <QDir>
#include <QFileInfo>
#include <QStringList>
#include <QDebug>
#include <lib-bianbu-control-center/interface/interface.h>
#include <QPluginLoader>
#include <QSysInfo>

static bool installTranslatorEarly(const QLocale &locale, QCoreApplication &app)
{
    const QString langCode = locale.name();
    const QString shortLang = langCode.section('_', 0, 0);

    QString tmpl = QString("/usr/share/locale/%1/LC_MESSAGES/bianbu-accounts.qm");
    QString primary = tmpl.arg(langCode);
    QString fallback;
    if (shortLang != langCode) {
        fallback = tmpl.contains("%1") ? tmpl.arg(shortLang) : QString();
    }

    QStringList candidates;
    candidates << primary;
    if (!fallback.isEmpty()) candidates << fallback;

    auto *translator = new QTranslator(&app);
    for (const QString &p : candidates) {
        if (!p.isEmpty() && QFileInfo::exists(p) && translator->load(p)) {
            QCoreApplication::installTranslator(translator);
            qDebug() << "[i18n] Installed translator from" << p << "for locale" << langCode;
            return true;
        }
    }
    translator->deleteLater();
    qDebug() << "[i18n] No translation file found for" << langCode << "(candidates:" << candidates << ")";
    return false;
}

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    installTranslatorEarly(QLocale(), app);

    QStringList candidates;
    QString arch = QSysInfo::currentCpuArchitecture();
    candidates << QString("/usr/lib/%1-linux-gnu/bianbu-control-center/libbianbu-accounts.so").arg(arch);
    candidates << QString("/usr/lib/bianbu-control-center/libbianbu-accounts.so");
    candidates << QCoreApplication::applicationDirPath() + "/libbianbu-accounts.so";

    QObject *pluginObj = nullptr;
    QPluginLoader loader;
    for (const QString &p : candidates) {
        loader.setFileName(p);
        if (QFileInfo::exists(p) && loader.load()) {
            pluginObj = loader.instance();
            qDebug() << "[plugin] Loaded" << p;
            break;
        } else {
            qDebug() << "[plugin] Failed" << p << loader.errorString();
        }
    }
    if (!pluginObj) {
        qCritical() << "Failed to load accounts plugin .so";
        return 1;
    }

    auto *pluginIf = qobject_cast<BianbuControlCenter::PluginInterface*>(pluginObj);
    if (!pluginIf) {
        qCritical() << "Loaded object is not a BianbuControlCenter PluginInterface";
        return 2;
    }

    QWidget *page = pluginIf->pluginUi();
    QMainWindow win;
    win.setWindowIcon(pluginIf->icon());
    win.setWindowTitle(pluginIf->pluginI18nName());
    win.setCentralWidget(page);
    win.setMinimumSize(660, 590);
    win.resize(660, 590);
    win.show();
    return app.exec();
}
