//
// Created by 张雪明 <zhangxueming@uniontech.com> on 2024/1/29.
//
#include "AuthorityUtils.h"
#include <polkit-qt6-1/PolkitQt1/Authority>
#include <QDebug>

using namespace PolkitQt1;

AuthorityWorker::AuthorityWorker()
{
}

AuthorityWorker::~AuthorityWorker()
{}

void AuthorityWorker::authorization(int type)
{
    bool result = this->checkAuthority("com.deepin.uosrecovery.checkAuthentication", getpid());
    Q_EMIT notifyAdminAuthority(result, type);
}

void AuthorityWorker::checkCommonUserAuthentication(int type)
{
    bool result = this->checkAuthority("com.deepin.uosrecovery.checkCommonUserAuthentication", getpid());
    Q_EMIT this->notifyCommonUserAuthority(result, type);
}

bool AuthorityWorker::checkAuthority(const QString &actionId, qint64 pid)
{
    Authority::Result result;
    result = Authority::instance()->checkAuthorizationSync(actionId,
                                                           UnixProcessSubject(pid),
                                                           Authority::AllowUserInteraction);
    return (result == PolkitQt1::Authority::Yes);
}

AuthorityUtils::AuthorityUtils()
{
    m_adminAuthWorker.moveToThread(&m_adminAuthThread);
    connect(&m_adminAuthWorker, &AuthorityWorker::notifyAdminAuthority, this, &AuthorityUtils::notifyAdminAuthority);
    connect(this, &AuthorityUtils::checkAdminAuthority, &m_adminAuthWorker, &AuthorityWorker::authorization);
    m_adminAuthThread.start();

    m_commonUserAuthWorker.moveToThread(&m_commonUserAuthThread);
    connect(&m_commonUserAuthWorker, &AuthorityWorker::notifyCommonUserAuthority,this, &AuthorityUtils::notifyCommonUserAuthority);
    connect(this, &AuthorityUtils::checkCommonUserAuthority, &m_commonUserAuthWorker, &AuthorityWorker::checkCommonUserAuthentication);
    m_commonUserAuthThread.start();
}

AuthorityUtils::~AuthorityUtils()
{
}

void AuthorityUtils::authorization(AuthorityType type)
{
    Q_EMIT checkAdminAuthority(static_cast<int>(type));
}

void AuthorityUtils::checkCommonUserAuthentication(AuthorityType type)
{
    Q_EMIT checkCommonUserAuthority(static_cast<int>(type));
}
