#include "proto_adapter.h"
#include <saas/protos/rtyserver.pb.h>
#include <saas/indexerproxy/context/action_reply.h>
#include <saas/indexerproxy/context/document.h>
#include <saas/indexerproxy/server/request_opts.h>
#include <saas/indexerproxy/adapters/json/json_adapter.h>

namespace NIndexerProxy {

    const TString TProtoAdapter::AdapterAlias("proto_rty");

    bool TProtoAdapter::ParseMessage(ISenderTask& context) const {
        const TBlob& post = context.GetContext().GetPost();
        NRTYServer::TMessage message;
        if (!message.ParseFromArray(post.AsCharPtr(), post.Size())) {
            DEBUG_LOG << "action=new_message;status=failed;service=" << context.GetContext().GetServiceName() << ";id_request=" << context.GetRequestId() << Endl;
            message.SetMessageId((ui64)-1);
            RETURN_ERROR("An error occurred while parsing protobuf");
            return false;
        }

        auto doc = MakeAtomicShared<TDispatchableDocument>(context);
        doc->MutableMessage()->CopyFrom(message);
        doc->MutableMessage()->SetMessageId(context.GetContext().GetRequestOptions().GetWaitReply() ? context.GetRequestId() : 0);

        context.GetContext().GetDocument() = doc;
        return true;
    }

    TAdaptersFactory::TRegistrator<NIndexerProxy::TProtoAdapter> NIndexerProxy::TProtoAdapter::Registrator(NIndexerProxy::TProtoAdapter::AdapterAlias);
}
