#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QWindow>
#include <QDebug>
#include <unistd.h>
#include <sys/stat.h>
#include <iostream>
#include <QDir>
#include <fcntl.h>
#include <QDebug>
#include <QSettings>
#include <QQmlContext>
#include <QTranslator>
#include <QQuickWindow>
#include <QtCore>
#include <QObject>
#include <QScreen>
#include <unistd.h>
#include "processmanager.h"
#include "xatom-helper.h"
#include "windowmanager/windowmanager.h"
#include "ukuistylehelper/ukuistylehelper.h"
#include "../src/common-tool/comm_func.h"

#define PROC_CPUINFO "/proc/cpuinfo"

void qtVersionHandle()
{
#if (QT_VERSION >= QT_VERSION_CHECK(5, 6, 0))
    QGuiApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    QGuiApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
#endif

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

void qtScaleHandle()
{
    Display *display = XOpenDisplay(nullptr);
    int dpi = QString::fromLatin1(XGetDefault(display, "Xft", "dpi")).toInt();
    XCloseDisplay(display);
    if (dpi <= 0) {
        dpi = 96;
    }
    double scale =  (double) dpi / 96.0;
    qputenv("QT_SCALE_FACTOR", QVariant(scale).toByteArray());
}


// 单例文件锁
bool fileLock()
{
    uid_t user;
    user = geteuid();
    QDir dir("/tmp/ukui-new-function-introduction/");
    if(dir.exists()) {
        QString lockPath = "/tmp/ukui-new-function-introduction/ukui-new-function-introduction-"+QString::number(user)+".lock";
        umask(0000);
        int fd = open(lockPath.toUtf8().data(), O_RDWR | O_CREAT | O_TRUNC,0666);
        if (fd < 0) {
            qDebug()<<"单例文件锁打开异常";
            qDebug()<<"1";
            exit(0);
        }
        return lockf(fd, F_TLOCK, 0);
    } else {
        dir.mkdir("/tmp/ukui-new-function-introduction/");//只创建一级子目录，即必须保证上级目录存在
        chmod("/tmp/ukui-new-function-introduction/",0777);
        QString lockPath = "/tmp/ukui-new-function-introduction/ukui-new-function-introduction-"+QString::number(user)+".lock";
        umask(0000);
        int fd = open(lockPath.toUtf8().data(), O_RDWR | O_CREAT | O_TRUNC,0666);
        if (fd < 0) {
            qDebug()<<"单例文件锁打开异常";
            exit(0);
        }
        return lockf(fd, F_TLOCK, 0);
    }
}

// 启动检测配置文件
bool readStartConf()
{
    QString lockPath = QDir::homePath() + "/.config/ukui/ukui-new-function-introduction.conf";
    umask(0000);
    int fd = open(lockPath.toUtf8().data(), O_RDWR | O_TRUNC,0666);
    if (fd < 0) {
        fd = open(lockPath.toUtf8().data(), O_RDWR | O_CREAT | O_TRUNC,0666);
        return true;
    } else {
        return false ;
    }
}

// 判断是否为wayland环境
bool isWaylandEnvironment()
{
    if (qgetenv("WAYLAND_DISPLAY").isEmpty()) {
        return false;
    } else {
        return true;
    }
}

bool getIs990()
{
    bool is990 = false;
    QRegExp r1("kirin.*9.0");
    r1.setCaseSensitivity(Qt::CaseInsensitive);
    QRegExp r2("pangu.*m900");
    r2.setCaseSensitivity(Qt::CaseInsensitive);

    QFile file(PROC_CPUINFO);
    if (!file.exists()) {
        is990 = false;
        return is990;
    }
    file.open(QFile::ReadOnly);
    QString str(file.readAll());
    is990 = (str.contains(r1) || str.contains(r2));
    file.close();

    if (is990)
        qDebug() << "is 990";

    return is990;
}

int main(int argc, char *argv[])
{
    double scale = 1.0;
    if (getIs990()) {
        qputenv("QT_QUICK_BACKEND","software");
        // 只有华为机型才需要重新适配缩放
        qtScaleHandle();
        scale = QString(qgetenv("QT_SCALE_FACTOR")).toDouble();
        qDebug() << scale;
        QStringList args= {"-platform","wayland"};
        for (const QString &arg : args) {
            char *argvCstr = strdup(arg.toUtf8().constData());
            argv[argc] =  argvCstr;
            argc++;
        }
        for (int i = 0; i < argc; i++) {
            qDebug() << "Argument " << i << ": " << QString::fromUtf8(argv[i]);
        }
    }
    QString arg = QString::fromUtf8(argv[1]);
    qtVersionHandle();

    if (!fileLock()) {
        if (arg == "-nocheck") {
            qDebug()<<"不用检查";
            QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);

            QGuiApplication app(argc, argv);
            QScreen *screen = QGuiApplication::primaryScreen();
            app.setWindowIcon(QIcon::fromTheme("kylin-new-function-introduction"));
            QCoreApplication::setApplicationName("kylin-new-function-introduction");
            qmlRegisterType<processmanager>("org.username", 1, 0, "ProcessManager");
            qRegisterMetaType<processmanager*>("p*");

            QString qm_name = QLocale::system().name();
            QTranslator translator;
            QTranslator trans;
            if(qm_name == "zh_CN" || qm_name == "es" || qm_name == "fr" || qm_name == "de" || qm_name == "ru" || qm_name == "bo_CN" || qm_name == "mn_MN" || qm_name ==  "zh_HK" || qm_name == "vi_VN") {//中文 西班牙语 法语 德语 俄语
                if(!translator.load("kylin-user-guide_" + qm_name + ".qm", "/usr/share/kylin-user-guide/translations/")) {
                    qDebug() << "Load translation file："<< "kylin-user-guide_" + qm_name + ".qm" << " failed!";
                } else {
                    app.installTranslator(&translator);
                }

                // sdk翻译加载
                if(trans.load(":/translations/gui_"+qm_name+".qm"))
                {
                    app.installTranslator(&trans);
                }
            }

            QQmlApplicationEngine engine;
            const QUrl url(QStringLiteral("qrc:/main.qml"));
            QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
                             &app, [url](QObject *obj, const QUrl &objUrl) {
                if (!obj && url == objUrl)
                    QCoreApplication::exit(-1);
            }, Qt::QueuedConnection);
            engine.load(url);
            engine.rootContext()->setContextProperty("p", new processmanager());

            app.setWindowIcon(QIcon::fromTheme("ukui-new-function-introduction"));
            QQuickWindow *window = qobject_cast<QQuickWindow *>(engine.rootObjects().at(0));
            kdk::WindowManager::setGeometry(window,QRect(((screen->size().width()-NEWFUNCTION_INTRODUCE_WIDTH)/2)*scale,((screen->size().height()-NEWFUNCTION_INTRODUCE_HEIGHT)/2)*scale,NEWFUNCTION_INTRODUCE_WIDTH,NEWFUNCTION_INTRODUCE_HEIGHT));
            if (window) {
                // 设置窗口标题
                window->setTitle(QObject::tr("kylin-new-function-introduction"));
                window->setIcon(QIcon::fromTheme("kylin-new-function-introduction"));
                // 设置固定窗口大小
                window->setMinimumSize(QSize(NEWFUNCTION_INTRODUCE_WIDTH, NEWFUNCTION_INTRODUCE_HEIGHT));
                window->setMaximumSize(QSize(NEWFUNCTION_INTRODUCE_WIDTH, NEWFUNCTION_INTRODUCE_HEIGHT));
            }

            return app.exec();
        } else {
            if (readStartConf()) {
                QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);

                QGuiApplication app(argc, argv);
                QScreen *screen = QGuiApplication::primaryScreen();
                app.setWindowIcon(QIcon::fromTheme("kylin-new-function-introduction"));
                QCoreApplication::setApplicationName("kylin-new-function-introduction");
                qmlRegisterType<processmanager>("org.username", 1, 0, "ProcessManager");
                qRegisterMetaType<processmanager*>("p*");

                QString qm_name = QLocale::system().name();
                QTranslator translator;
                QTranslator trans;
                if(qm_name == "zh_CN" || qm_name == "es" || qm_name == "fr" || qm_name == "de" || qm_name == "ru" || qm_name == "bo_CN" || qm_name == "mn_MN" || qm_name ==  "zh_HK" || qm_name == "vi_VN") {//中文 西班牙语 法语 德语 俄语
                    if(!translator.load("kylin-user-guide_" + qm_name + ".qm", "/usr/share/kylin-user-guide/translations/")) {
                        qDebug() << "Load translation file："<< "kylin-user-guide_" + qm_name + ".qm" << " failed!";
                    } else {
                        app.installTranslator(&translator);
                    }

                    // sdk翻译加载
                    if(trans.load(":/translations/gui_"+qm_name+".qm"))
                    {
                        app.installTranslator(&trans);
                    }
                }

                QQmlApplicationEngine engine;
                const QUrl url(QStringLiteral("qrc:/main.qml"));
                QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
                                 &app, [url](QObject *obj, const QUrl &objUrl) {
                    if (!obj && url == objUrl)
                        QCoreApplication::exit(-1);
                }, Qt::QueuedConnection);
                engine.load(url);
                engine.rootContext()->setContextProperty("p", new processmanager());

                QQuickWindow *window = qobject_cast<QQuickWindow *>(engine.rootObjects().at(0));
                kdk::WindowManager::setGeometry(window,QRect(((screen->size().width()-NEWFUNCTION_INTRODUCE_WIDTH)/2)*scale,((screen->size().height()-NEWFUNCTION_INTRODUCE_HEIGHT)/2)*scale,NEWFUNCTION_INTRODUCE_WIDTH,NEWFUNCTION_INTRODUCE_HEIGHT));
                if (window) {
                    // 设置窗口标题
                    window->setTitle(QObject::tr("kylin-new-function-introduction"));
                    window->setIcon(QIcon::fromTheme("kylin-new-function-introduction"));
                    // 设置固定窗口大小
                    window->setMinimumSize(QSize(NEWFUNCTION_INTRODUCE_WIDTH, NEWFUNCTION_INTRODUCE_HEIGHT));
                    window->setMaximumSize(QSize(NEWFUNCTION_INTRODUCE_WIDTH, NEWFUNCTION_INTRODUCE_HEIGHT));
                }
                return app.exec();
            } else {
                qDebug()<<"The demo program has been started. If you want to start it again, please execute [ ukui-new-function-introduction -nocheck] ";
                return 0;
            }
        }

    } else {
        qDebug()<< "ukui-new-function-introduction is running";
    }
}
