/*
 * Copyright (C) 2023, KylinSoft Co., Ltd.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <http://www.gnu.org/licenses/>.
 *
**/
#include "mainwindow.h"

#include <QApplication>
#include <QtSingleApplication>
#include <QTranslator>
#include <QObject>
#include <QDebug>
#include <QSharedPointer>
#include <memory>
#include <QCommandLineParser>
#include <QQuickWidget>
#include <QStandardPaths>
#include <QTime>
#include <KWindowEffects>
#include <signal.h>
#include <stdlib.h>
#include <ukuistylehelper/ukuistylehelper.h>
#include <QSessionManager>

#ifdef KYDEBUG
#ifndef __sw_64__
#include <ukui-log4qt.h>
#endif
#endif

#include "framelessExtended/framelesshandle.h"
#include "customstyle.h"
#include "interface/ukcccommon.h"
using namespace ukcc;
#include "utils/xatom-helper.h"
#include "ukccsearchserver.h"

const QString KLong = "Loongson";

MainWindow *mainWindow = nullptr;

void sigExit(int signalNum)
{
    if (mainWindow != nullptr) {
        mainWindow->close();
    }
}

int main(int argc, char *argv[])
{
    signal(SIGINT,sigExit);
#ifdef KYDEBUG
#ifndef __sw_64__
    initUkuiLog4qt("ukui-control-center");
#endif
#endif
    QApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    QApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);

    if (UkccCommon::getCpuInfo().startsWith(KLong, Qt::CaseInsensitive)) {
        QQuickWindow::setSceneGraphBackend(QSGRendererInterface::Software);
    }

#if (QT_VERSION >= QT_VERSION_CHECK(5, 14, 0))
    QApplication::setHighDpiScaleFactorRoundingPolicy(Qt::HighDpiScaleFactorRoundingPolicy::PassThrough);
#endif

    QString id = QString("ukui-control-center" + QLatin1String(getenv("DISPLAY")));
    QtSingleApplication a(id, argc, argv);

    if (a.isRunning()) {
        int agr_length = QApplication::arguments().length();
        a.sendMessage(QApplication::arguments().length() > 1 ? QApplication::arguments().at(agr_length-1) : a.applicationFilePath());
        qDebug() << QObject::tr("ukui-control-center is already running!");
        return EXIT_SUCCESS;
    } else {
        //控制面板是否被禁用
        if (UkccCommon::isTablet()) {
            QString m_initPath =  QString("%1/%2/%3").arg(QDir::homePath()).arg(".cache/ukui-menu").arg("ukui-menu.ini");
            QSettings settings(m_initPath, QSettings::IniFormat);
            settings.beginGroup("application");
            if (settings.contains("ukui-control-center")){
                bool isRun = settings.value("application/ukui-control-center").toBool();
                if (!isRun) {
                    qDebug() << QObject::tr("ukui-control-center is disabled！");
                    return EXIT_SUCCESS;
                }
            }
            settings.sync();
            settings.endGroup();
        }
        // 加载国际化文件
        QTranslator translator;
        translator.load("/usr/share/ukui-control-center/shell/res/i18n/" + QLocale::system().name());
        a.installTranslator(&translator);

        // sdk翻译加载
        QTranslator trans;
        if(trans.load(":/translations/gui_"+QLocale::system().name()+".qm"))
        {
            a.installTranslator(&trans);
        }

        // 加载 qt 翻译
        QTranslator qttranslator;
        if(!qttranslator.load(QLocale(), "qt", "_", "/usr/share/qt5/translations/")) {
            qDebug() << "Load qt translation file："<< QString("usr/share/qt5/translations/%1.qm").arg(QLocale::system().name()) << " failed!";
        } else {
            a.installTranslator(&qttranslator);
            qDebug()<<"load qt translation file success";
        }
        // 命令行参数
        QCoreApplication::setApplicationName(QObject::tr("ukui-control-center"));
        QCoreApplication::setApplicationVersion("2.0");

        QCommandLineParser parser;
        QCommandLineOption moduleOption(QStringList() << "m", "display the specified module page", "module");
        QCommandLineOption moduleOption_p(QStringList() << "p", "load the specified plugin", "plugin");
        QCommandLineOption dbusOption(QStringList() << "d" << "dbus", "startup on dbus");

        parser.addHelpOption();
        parser.addVersionOption();
        parser.addOption(dbusOption);
        parser.addOption(moduleOption);
        parser.addOption(moduleOption_p);
        parser.process(a);

        MainWindow w;
        mainWindow = &w;
        if (!UkccCommon::isOpenkylin())
            UkccCommon::centerToScreen(&w);

        w.setAttribute(Qt::WA_TranslucentBackground);

        kdk::UkuiStyleHelper::self()->removeHeader(&w);
        KWindowEffects::enableBlurBehind(w.winId(),true);

        QDBusConnection connection = QDBusConnection::sessionBus();
        if (!connection.registerService("org.ukui.ukcc.search")) { // 注册服务
            qDebug() << "register ukcc search service error:" << connection.lastError().message();
            return EXIT_FAILURE;
        }
        UkccSearchServer search_obj(mainWindow);
        connection.registerObject("/", &search_obj, QDBusConnection::ExportAllSlots);

        const QByteArray id("org.ukui.session");
        if (QGSettings::isSchemaInstalled(id)) {
            QGSettings *sessionGesstings = new QGSettings(id, QByteArray());
            if (sessionGesstings->get("restore-session").toBool()) {
                QGuiApplication::setFallbackSessionManagementEnabled(true);
                QGuiApplication::setQuitOnLastWindowClosed(false);
            }
            QObject::connect(sessionGesstings,&QGSettings::changed, [=](QString key){
                qDebug() << "key =" << key;
                if (key == "restoreSession") {
                    QGuiApplication::setFallbackSessionManagementEnabled(sessionGesstings->get("restore-session").toBool());
                    QGuiApplication::setQuitOnLastWindowClosed(!sessionGesstings->get("restore-session").toBool());
                }
            });
        }

        a.setActivationWindow(&w);
        QObject::connect(&a, SIGNAL(messageReceived(const QString&)), &w, SLOT(sltMessageReceived(const QString&)));
        if (!parser.isSet(dbusOption)) {
            w.initPageWidget();
            w.show();
        }

        return a.exec();
    }
}
