#include "bootinterface.h"
#include <QThreadPool>
#include <QGSettings>
#include <kysdk/kysdk-system/libkysysinfo.h>

BootInterface::BootInterface():UKUI::ServiceObject(nullptr), QDBusContext()
{
    QDBusInterface m_pUkccSystemDbus("com.control.center.qt.systemdbus",
                                      "/",
                                      "com.control.center.interface",
                                      QDBusConnection::systemBus(), this);

    if (!isSameSystems()) {
        QGSettings ukcc(UKCC_SCHAME);
        // 获取到当前系统不一致，设置gsetting提供给前端取消勾选
        ukcc.set(SYSTEMS_SAME, false);

        QString lang = qgetenv("LANG");
        m_pUkccSystemDbus.call("updateGrub", lang);
    }
}

BootInterface::~BootInterface()
{
}

bool BootInterface::isSameSystems()
{
    // 1.获取当前/boot/grub/grub.cfg文件中启动项
    QString grubMenus(kdk_system_get_grub_menu());
    grubMenus.remove("\"");
    grubMenus.remove("{");
    grubMenus.remove("}");

    qDebug() << "get boot list = " << grubMenus;
    QStringList grubMenuItem =  grubMenus.split(",");
    int gotSystems = 0;
    // 2.windows不存在os-release，判断方式为linux判断方式，去掉列表中windows
    for (int i = 0; i < grubMenuItem.count(); i++) {
        QString tmp = grubMenuItem[i];
        QStringList item = tmp.split(":");
        if (item.size() >= 2) {
            qDebug() << "grub menu type :" << item.at(1);
            if (item.at(1) == "menuentry") {
                qDebug() << "grub menu :" << item.at(0);
                if (!QString(item.at(0)).contains("windows", Qt::CaseInsensitive)) {
                    gotSystems++;
                }
            }
        }
    }

    // 3.根据挂载目录/etc/os-release获取实际存在os数，windows不存在os-release
    int actualSystems = 0;
    QList<QStorageInfo> storelist = QStorageInfo::mountedVolumes();
    foreach (const QStorageInfo &storea, storelist) {
        qDebug() << "device:" << storea.device() << "path:" << storea.rootPath();
        QFile file(QString(storea.rootPath()+"/etc/os-release"));
        if (file.exists()) {
            actualSystems++;
        }
    }

    // 4.比较sdk接口获取与实际os数，更新grub
    qDebug() << "gotsystems = " << gotSystems << "actualsystems = " << actualSystems;
    if (gotSystems == actualSystems) {
        return true;
    }
    return false;
}

