//
// Created by zxm on 2022/12/23.
//
#include "BRContext.h"
#include <mutex>
#include <QDBusMetaType>

Context::Context() : operateID(""), userName(""), opType(-1)
{
    Context::registerMetaType();
}

Context::Context(const QString &opID, const QString &name, const int &type)
    : operateID(opID), userName(name), opType(type)
{
    Context::registerMetaType();
}

Context& Context::operator=(const Context &other)
{
    if (this != &other) {
        this->operateID = other.operateID;
        this->userName = other.userName;
        this->opType = other.opType;
    }

    return *this;
}

void Context::registerMetaType()
{
    qRegisterMetaType<Context>("Context");
    qDBusRegisterMetaType<Context>();
}

QDBusArgument& operator<<(QDBusArgument &arg, const Context &ctx)
{
    arg.beginStructure();
    arg << ctx.operateID
        << ctx.userName
        << ctx.opType;
    arg.endStructure();
    return arg;
}

const QDBusArgument& operator>>(const QDBusArgument &arg, Context &ctx)
{
    arg.beginStructure();
    arg >> ctx.operateID
        >> ctx.userName
        >> ctx.opType;
    arg.endStructure();
    return arg;
}

BRContext::BRContext() : m_isRun(false)
{

}

bool BRContext::isRunning()
{
    URReadLockGuard<URRWLock> lock(m_isRunSharedMutex);
    return m_isRun;
}

void BRContext::setRun(bool run)
{
    {
        URWriteLockGuard<URRWLock> lock(m_isRunSharedMutex);
        m_isRun = run;
    }

    if (!run) {
        Context resetCtx("", "", -1);
        this->setContext(resetCtx);
    }
}

void BRContext::setContext(const Context &ctx)
{
    URWriteLockGuard<URRWLock> lock(m_contextSharedMutex);
    m_context = ctx;
}

Context BRContext::getContext()
{
    URReadLockGuard<URRWLock> lock(m_contextSharedMutex);
    return m_context;
}
