#include "KMFolder.h"

#include "KMLogger.h"
#include "KMPermissionConfig.h"
#include "KMUtil.h"

using namespace std;

class KMPermissionConfig::Private
{
public:
    string m_appId;
    PermissionFlags m_flags = static_cast<PermissionFlags>(static_cast<int>(Perm_Network) | static_cast<int>(Perm_Camera) | static_cast<int>(Perm_Filesystem));

    set<string> m_disabledDbus;
};

KMPermissionConfig::KMPermissionConfig(token, const string &id)
    : m_dPtr(make_shared<Private>())
{
    m_dPtr->m_appId = id;
    init();
}

KMPermissionConfig::~KMPermissionConfig() { }

KMPermissionConfig::PermissionFlags KMPermissionConfig::getFlags()
{
    return m_dPtr->m_flags;
}

std::set<std::string> KMPermissionConfig::getDisabledDBus()
{
    return m_dPtr->m_disabledDbus;
}

/// @brief 加载配置文件
void KMPermissionConfig::init()
{

    if (!fs::exists(KMFolder::getHomePath() / ".config/kaiming-permission.ini"))
    {
        ofstream outfile(KMFolder::getHomePath() / ".config/kaiming-permission.ini");
    }

    if (!loadFile(KMFolder::getHomePath() / ".config/kaiming-permission.ini"))
    {
        return;
    }

    if (keyExists(m_dPtr->m_appId, "network") && !getBoolValue(m_dPtr->m_appId, "network"))
    {
        m_dPtr->m_flags = static_cast<PermissionFlags>(static_cast<int>(m_dPtr->m_flags) & ~static_cast<int>(Perm_Network));
    }

    if (keyExists(m_dPtr->m_appId, "camera") && !getBoolValue(m_dPtr->m_appId, "camera"))
    {
        m_dPtr->m_flags = static_cast<PermissionFlags>(static_cast<int>(m_dPtr->m_flags) & ~static_cast<int>(Perm_Camera));
    }

    if (keyExists(m_dPtr->m_appId, "filesystem") && !getBoolValue(m_dPtr->m_appId, "filesystem"))
    {
        m_dPtr->m_flags = static_cast<PermissionFlags>(static_cast<int>(m_dPtr->m_flags) & ~static_cast<int>(Perm_Filesystem));
    }

    for (auto dbus : getStringListValueWithQMarks(m_dPtr->m_appId, "disbale_session_bus"))
    {
        if (dbus.length() > 0)
        {
            m_dPtr->m_disabledDbus.insert(dbus);
        }
    }

    for (auto dbus : getStringListValueWithQMarks(m_dPtr->m_appId, "disable_system_bus"))
    {
        if (dbus.length() > 0)
        {
            m_dPtr->m_disabledDbus.insert(dbus);
        }
    }
}
