#include "async_sender_task.h"
#include "sender_executor.h"

#include <saas/util/logging/tskv_log.h>
#include <saas/util/destroyer.h>
#include <saas/protos/rtyserver.pb.h>

#include <library/cpp/string_utils/base64/base64.h>

TAsyncSenderTask::TAsyncSenderTask(TTaskExecutor& executor, TFinishExecutor& finishExecutor, IAdapterContext* context, TStaticServiceMetrics& metrics, ISenderTask::TDestroyer& destroyer)
    : TCommonSenderTask(executor, finishExecutor, context, metrics, destroyer)
{
    DEBUG_LOG << "async constr" << Endl;
}

int TAsyncSenderTask::DoFillDocuments(TAdaptersManager& /*processor*/) {
    NRTYServer::TRequestTracer tracer;
    DEBUG_LOG << "async processing" << Endl;
    try {
        TString data = Base64Decode(TStringBuf(GetContext().GetPost().AsCharPtr(), GetContext().GetPost().Size()));
        if (!tracer.ParseFromString(data))
            ythrow yexception() << "cannot deserialize description";
    } catch (const yexception& e) {
        GetReply().SetInfo(NRTYServer::TReply::dsUSER_ERROR, TString("trace incorrect: ") + e.what());
        DEBUG_LOG << "action=read_from_trace;status=finished;docs_exists=" << !!Context->GetDocument() << ";result=" << 400 << ";service=" << Context->GetServiceName() << ";client_id=" << ClientId << Endl;
        return 400;
    }

    if (tracer.DocumentsSize() > 1) {
        GetReply().SetInfo(NRTYServer::TReply::dsUSER_ERROR, "trace incorrect: documents count > 1");
        DEBUG_LOG << "action=read_from_trace;status=finished;docs_exists=" << !!Context->GetDocument() << ";result=" << 400 << ";service=" << Context->GetServiceName() << ";client_id=" << ClientId << Endl;
        return 400;
    }

    if (tracer.DocumentsSize() == 1) {
        GetContext().GetDocument().Reset(new TDispatchableDocument(*this));
        *GetContext().GetDocument()->MutableMessage() = tracer.GetDocuments(0).GetMessage();
        DEBUG_LOG << "Continuing process task with id=" << tracer.GetDocuments(0).GetId() << " as " << GetRequestId() << Endl;
        Trace.Deserialize(&tracer.GetDocuments(0));
    }
    return 200;
}
