#include "message_bus/pipeline/stages/1_framers/PassthroughFramer.h"

#include <cstring>

namespace softbus::message_bus::pipeline::stages::framers
{

PassthroughFramer::PassthroughFramer(std::shared_ptr<softbus::core::memory::MemoryPool> pool)
    : m_pool(std::move(pool))
{
}

void PassthroughFramer::feed(softbus::core::models::RawBusMessage&           chunkIn,
                             std::vector<softbus::core::models::RawBusMessage>& completeFramesOut)
{
    if (!m_pool || !chunkIn.payload.valid()) {
        return;
    }
    const std::size_t n = chunkIn.payload.length;
    if (n == 0) {
        return;
    }
    auto blk = m_pool->allocate(n);
    if (!blk || !blk->data || blk->capacity < n) {
        return;
    }
    const std::uint8_t* src = chunkIn.payload.bytes();
    if (!src) {
        return;
    }
    std::memcpy(blk->data, src, n);
    blk->size = n;

    softbus::core::models::RawBusMessage out;
    out.deviceId = chunkIn.deviceId;
    out.endpointHash = chunkIn.endpointHash;
    out.protocol = chunkIn.protocol;
    out.logicalAddress = chunkIn.logicalAddress;
    out.routingKey = chunkIn.routingKey;
    out.header = chunkIn.header;
    out.timestampMs = chunkIn.timestampMs;
    out.traceId = chunkIn.traceId;
    out.direction = chunkIn.direction;
    out.payload.block = std::move(blk);
    out.payload.offset = 0;
    out.payload.length = n;

    completeFramesOut.push_back(std::move(out));
    chunkIn.payload = {};
}

} // namespace softbus::message_bus::pipeline::stages::framers
