#include <softbus_transport/TransportBusBridge.h>

#include <softbus_core/logging/Logger.h>

namespace softbus::transport {

void TransportBusBridge::attach(softbus::bus::Bus* bus, TcpUplinkServer* server)
{
    bus_ = bus;
    server_ = server;
    if (!bus_ || !server_) {
        return;
    }

    server_->setWireMessageHandler([this](const WireMessage& msg) {
        onWireMessage(msg);
    });

    cmdSub_ = bus_->subscribe("control/cmd/#", [this](const softbus::bus::BusMessage& msg) {
        onBusMessage(msg);
    });
    bus_->subscribe("control/cmd/injected", [this](const softbus::bus::BusMessage& msg) {
        onBusMessage(msg);
    });
}

void TransportBusBridge::onBusMessage(const softbus::bus::BusMessage& message)
{
    if (!server_ || message.type != softbus::bus::BusPayloadType::ExecuteCommand) {
        return;
    }
    if (!server_->sendCommand(message.command)) {
        SB_LOG_WARN("TransportBusBridge", "failed to send command to edge topic=", message.topic);
    }
}

void TransportBusBridge::onWireMessage(const WireMessage& message)
{
    if (!bus_) {
        return;
    }

    softbus::bus::BusMessage busMsg;
    switch (message.type) {
    case WireMessageType::RawPacket:
        busMsg.type = softbus::bus::BusPayloadType::RawPacket;
        busMsg.rawPacket = message.rawPacket;
        bus_->publish("edge/raw/" + message.rawPacket.sourceId, busMsg);
        break;
    case WireMessageType::Ack:
        busMsg.type = softbus::bus::BusPayloadType::Ack;
        busMsg.ack = message.ack;
        bus_->publish("control/ack/" + message.ack.deviceId + "/" + message.ack.pointId, busMsg);
        break;
    case WireMessageType::Heartbeat:
        busMsg.type = softbus::bus::BusPayloadType::Heartbeat;
        busMsg.deviceId = message.heartbeatDeviceId;
        bus_->publish("system/heartbeat/" + message.heartbeatDeviceId, busMsg);
        break;
    case WireMessageType::ExecuteCommand:
        busMsg.type = softbus::bus::BusPayloadType::ExecuteCommand;
        busMsg.command = message.command;
        bus_->publish("control/cmd/injected", busMsg);
        break;
    default:
        break;
    }
}

} // namespace softbus::transport
