#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::message_bus::pipeline::PipelineContext&           chunkIn,
                             std::vector<softbus::message_bus::pipeline::PipelineContext>& completeFramesOut)
{
    if (!m_pool || !chunkIn.payload.valid()) {
        return;
    }
    const std::size_t n = chunkIn.payloadSize ? chunkIn.payloadSize : 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::message_bus::pipeline::PipelineContext out;
    out.deviceId     = chunkIn.deviceId;
    out.stableKey    = chunkIn.stableKey;
    out.endpoint     = chunkIn.endpoint;
    out.timestamp    = chunkIn.timestamp;
    out.protocolHint = chunkIn.protocolHint;
    out.traceId      = chunkIn.traceId;
    out.direction    = chunkIn.direction;
    out.frameKind    = softbus::message_bus::pipeline::FrameKind::CompleteFrame;
    out.payloadSize  = n;
    out.payload.block = std::move(blk);
    out.payload.offset = 0;
    out.payload.length = n;

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

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