#include <QDebug>
#include <QIcon>
#include <QMessageBox>
#include <QFontDatabase>

#include <DLog>
#include <DWidgetUtil>
#include <DAboutDialog>
#include <DApplication>

#include "tool.h"

#include "view/mainwindow.h"

void loadFonts()
{
    using namespace Dtk::Widget;

#ifdef Q_OS_WIN
    QFontDatabase database;
    QStringList fontlist = database.families();

    QStringList preferList;
    preferList.append("Microsoft YaHei UI");
    preferList.append("SimHei");

    for (auto &font : preferList) {
        if (fontlist.contains(font)) {
            QFont newFont = QFont(font);
            newFont.setPixelSize(13);
            qApp->setFont(newFont);
            return;
        }
    }
#endif
}

void loadTranslator(QApplication &app)
{
    QTranslator *translator = new QTranslator();
    QString tnapplang;
    QString tnappcoun;
    QString clangcode = "";
    QStringList allappargs = app.arguments();
    QList<QPair<QString, QString> > oppairs;

    for (QList<QString>::const_iterator i = allappargs.constBegin(); i < allappargs.constEnd(); ++i) {
        if (i->count('=') == 1) {
            oppairs.append(QPair<QString, QString> (i->section('=', 0, 0).simplified(), i->section('=', 1, 1).simplified()));
        }
    }

    for (QList<QPair<QString, QString> >::const_iterator i = oppairs.constBegin(); i < oppairs.constEnd(); ++i) {
        if (i->first.contains("lang", Qt::CaseInsensitive)) {
            clangcode = i->second;
            tnapplang = clangcode.left(2);

            if (clangcode.contains('_') && clangcode.size() == 5) {
                tnappcoun = clangcode.section('_', -1, -1);
            }

            break;
        }
    }

    if (clangcode.isEmpty()) {
        clangcode = QLocale::system().name();
        tnapplang = clangcode.left(2);

        if (clangcode.contains('_') && clangcode.size() == 5) {
            tnappcoun = clangcode.section('_', -1, -1);
        }
    }

    QString tranlateUrl;
    if (!tnappcoun.isEmpty()) {
        tranlateUrl = QString(":/deepin-legalization-checker_%1_%2.qm").arg(tnapplang).arg(tnappcoun);
    }

    if (translator->load(tranlateUrl)) {
        qDebug() << "load:" << tranlateUrl;
        app.installTranslator(translator);
    } else {
        tranlateUrl = QString(":/deepin-legalization-checker_%1.qm").arg(tnapplang);
        if (translator->load(tranlateUrl)) {
            qDebug() << "load:" << tranlateUrl;
            app.installTranslator(translator);
        }
    }

    qDebug() << "locate:" << clangcode << tnappcoun;
    qDebug() << "current url:" << tranlateUrl;

    if (translator->load(tranlateUrl)) {
        qDebug() << "load:" << tranlateUrl;
        app.installTranslator(translator);
    }

    tranlateUrl = ":/dtkwidget2_zh_CN.qm";
    translator = new QTranslator();
    if (translator->load(tranlateUrl)) {
        qDebug() << "load:" << tranlateUrl;
        app.installTranslator(translator);
    }

    tranlateUrl = ":/qt_zh_CN.qm";
    translator = new QTranslator();
    if (translator->load(tranlateUrl)) {
        qDebug() << "load" << tranlateUrl;
        app.installTranslator(translator);
    }
}

#ifdef Q_OS_WIN

#define DeepinServiceName "Deepin Legalization Agent"
#include "servicemanager.h"

#endif

int main(int argc, char *argv[])
{
#if defined(DTK_STATIC_LIB)
    DWIDGET_INIT_RESOURCE();
#endif

    Dtk::Widget::DApplication::loadDXcbPlugin();
    Dtk::Widget::DApplication app(argc, argv);
    app.setOrganizationName("deepin");
    app.setApplicationName("deepin-legalization-checker");

    Dtk::Core::DLogManager::registerConsoleAppender();
    Dtk::Core::DLogManager::registerFileAppender();

    app.setApplicationVersion(Tool::getVersion());
    app.setWindowIcon(QIcon(":/image/logo_24.svg"));

    if (!Tool::setSingleInstance(app.applicationName())) {
        qWarning() << "anthorer instance is running!";
        return 0;
    }

    loadFonts();
    app.loadTranslator();

    loadTranslator(app);


    app.setApplicationDisplayName(QObject::tr("Deepin Legalization Checker"));
    app.setApplicationDescription(Dtk::Widget::DAboutDialog::tr("Deepin Legalization Checker is a tool for checking the legalization of operating system, by collecting operating system information and judging its genuine and activation status."));

    int delay = 0;
#ifdef Q_OS_WIN
    bool checkInstall = true;
    ServiceManager sc;
    if (sc.Open()) {
        if (!sc.Exist(DeepinServiceName)) {
            QString agentPath = app.applicationDirPath() + "/deepin-legalization-agent.exe";
            sc.Install(DeepinServiceName, agentPath);
            delay = 15 * 1000;
        }

        // check started
        if (!sc.IsRunning(DeepinServiceName)) {
            sc.Start(DeepinServiceName);
            delay = 15 * 1000;
        }
    }

    QMessageBox waitMsgBox;
    if (delay > 0) {
        waitMsgBox.setIcon(QMessageBox::Information);
        waitMsgBox.setMinimumWidth(400);
        waitMsgBox.setStandardButtons(0);
        waitMsgBox.setWindowFlags(waitMsgBox.windowFlags() & ~Qt::WindowCloseButtonHint);
        waitMsgBox.setText("正在启动服务，请稍后...");
        waitMsgBox.show();
    }
#endif

    QTimer::singleShot(delay, [ & ]() {

#ifdef Q_OS_WIN
        if (!sc.IsRunning(DeepinServiceName)) {
            checkInstall = false;
        }

        if (!checkInstall) {
            QMessageBox msg;
            msg.setIcon(QMessageBox::Critical);
            msg.setText("无法启动服务，这可能是软件安装失败导致。\n请关闭杀毒软件后重新安装软件，或者在杀毒软件拦截时点击允许。");
            msg.exec();
            app.quit();
        }
        waitMsgBox.hide();
#endif
        MainWindow *w = new MainWindow();
        w->show();
        Dtk::Widget::moveToCenter(w);
        w->raise();
        w->activateWindow();

        auto aboutDialog = new Dtk::Widget::DAboutDialog(w);
        aboutDialog->setProductName(app.productName());
        aboutDialog->setWebsiteName("www.deepin.com");
        aboutDialog->setWebsiteLink("https://www.deepin.com");
        aboutDialog->setAcknowledgementLink("https://www.deepin.com");
        aboutDialog->setProductIcon(app.productIcon());
        aboutDialog->setVersion(Dtk::Widget::DAboutDialog::tr("Version: %1").arg(app.applicationVersion()));

        aboutDialog->setDescription(app.applicationDescription());

        app.setAboutDialog(aboutDialog);
    });


    return app.exec();
}
