#include <softbus_daemon/pipeline/PipelineEngine.h>

#include <softbus_core/logging/Logger.h>

#include <vector>

namespace softbus::daemon {

PipelineEngine::PipelineEngine(softbus::core::PluginLoader* plugin, softbus::opcua::UaModelBinder* binder)
    : plugin_(plugin)
    , binder_(binder)
{
}

void PipelineEngine::process(const softbus::core::RawPacket& packet)
{
    if (!plugin_ || !plugin_->parser() || !binder_) {
        return;
    }

    const uint8_t* data = packet.payload.data();
    std::size_t size = packet.payload.size();
    std::vector<uint8_t> frame = packet.payload;

    if (plugin_->framer()) {
        const auto framed = plugin_->framer()->extract(data, size);
        if (framed.success) {
            frame = framed.frame;
            data = frame.data();
            size = frame.size();
        }
    }

    auto parsed = plugin_->parser()->parseFrame(data, size, packet.sourceId);
    if (!parsed.success) {
        SB_LOG_WARN_TRACE("PipelineEngine", packet.traceId, "Failed to parse RawPacket");
        return;
    }

    parsed.message.traceId = packet.traceId;
    parsed.message.timestampNs = packet.timestampNs;
    SB_LOG_INFO_TRACE("PipelineEngine", packet.traceId,
        "RawPacket converted to DOMMessage id=", parsed.message.id);
    binder_->bind(parsed.message);
}

} // namespace softbus::daemon
