#include "api/ipc_dbus/CommandDispatcher.h"

#include "message_bus/pipeline/DynamicRuleRegistry.h"

namespace softbus::api::ipc
{

namespace
{

softbus::message_bus::pipeline::RuleScope parseScope(const QJsonObject& params)
{
    softbus::message_bus::pipeline::RuleScope scope;
    scope.endpoint = params.value(QStringLiteral("endpoint")).toString();
    scope.deviceId = params.value(QStringLiteral("deviceId")).toInt(-1);
    scope.stableKey = params.value(QStringLiteral("stableKey")).toString();
    return scope;
}

} // namespace

DispatchResult CommandDispatcher::dispatch(const QString& action, const QJsonObject& params) const
{
    auto& reg = softbus::message_bus::pipeline::DynamicRuleRegistry::instance();
    if (action == QStringLiteral("add_filter")) {
        softbus::message_bus::pipeline::FilterRule rule;
        rule.id = params.value(QStringLiteral("id")).toString();
        rule.scope = parseScope(params);
        rule.condition = params.value(QStringLiteral("condition")).toObject();
        if (!reg.addFilterRule(rule)) {
            return {4001, QStringLiteral("invalid_filter_rule"), {}};
        }
        return {0, QStringLiteral("ok"), QJsonObject{{QStringLiteral("id"), rule.id}}};
    }
    if (action == QStringLiteral("remove_filter")) {
        const QString id = params.value(QStringLiteral("id")).toString();
        const bool ok = reg.removeFilterRule(id);
        return {ok ? 0 : 4041, ok ? QStringLiteral("ok") : QStringLiteral("filter_not_found"),
                QJsonObject{{QStringLiteral("id"), id}}};
    }
    if (action == QStringLiteral("add_transform_rule")) {
        softbus::message_bus::pipeline::TransformRule rule;
        rule.id = params.value(QStringLiteral("id")).toString();
        rule.scope = parseScope(params);
        rule.scale = params.value(QStringLiteral("scale")).toDouble(1.0);
        rule.offset = params.value(QStringLiteral("offset")).toDouble(0.0);
        rule.unit = params.value(QStringLiteral("unit")).toString();
        if (!reg.addTransformRule(rule)) {
            return {4002, QStringLiteral("invalid_transform_rule"), {}};
        }
        return {0, QStringLiteral("ok"), QJsonObject{{QStringLiteral("id"), rule.id}}};
    }
    if (action == QStringLiteral("remove_transform_rule")) {
        const QString id = params.value(QStringLiteral("id")).toString();
        const bool ok = reg.removeTransformRule(id);
        return {ok ? 0 : 4042, ok ? QStringLiteral("ok") : QStringLiteral("transform_rule_not_found"),
                QJsonObject{{QStringLiteral("id"), id}}};
    }
    if (action == QStringLiteral("list_rules") || action == QStringLiteral("get_status")) {
        return {0, QStringLiteral("ok"), reg.status()};
    }
    return {4040, QStringLiteral("unknown_action"), {}};
}

} // namespace softbus::api::ipc

