#include "message_bus/egress/EgressRouter.h"

#include "core/models/MessageRoutingUtils.h"
#include "devices/physical/SerialDevice.h"

namespace softbus::message_bus::egress
{

void EgressRouter::bindSerialDevice(
    const QString& endpoint,
    const QSharedPointer<softbus::devices::physical::SerialDevice>& device)
{
    m_serialByEndpoint.insert(endpoint, device);
}

void EgressRouter::unbindSerialDevice(const QString& endpoint)
{
    m_serialByEndpoint.remove(endpoint);
}

bool EgressRouter::send(const softbus::core::models::RawBusMessage& ctx)
{
    QSharedPointer<softbus::devices::physical::SerialDevice> device;
    for (auto it = m_serialByEndpoint.constBegin(); it != m_serialByEndpoint.constEnd(); ++it) {
        if (softbus::core::models::makeEndpointHash(it.key()) == ctx.endpointHash) {
            device = it.value();
            break;
        }
    }
    if (device.isNull() || !ctx.payload.valid()) {
        return false;
    }

    const auto* p = ctx.payload.bytes();
    if (!p) {
        return false;
    }
    return device->writePayload(p, ctx.payload.length);
}

} // namespace softbus::message_bus::egress
