#include "json_adapter.h"
#include <saas/indexerproxy/context/action_reply.h>
#include <saas/indexerproxy/server/request_opts.h>

#include <library/cpp/json/json_reader.h>
#include <library/cpp/json/json_writer.h>

using namespace NIndexerProxy;
using namespace NJson;

namespace {
    const size_t SizeLimit = 16 * 1024 * 1024;
}

bool TJsonAdapter::ParseMessage(ISenderTask& context) const {
    const TBlob& post = context.GetContext().GetPost();
    const size_t limit = Max<size_t>(SizeLimit, context.GetContext().GetRequestOptions().GetSizeLimit());
    if (post.Length() > limit) {
        RETURN_ERROR("Message size exceeds the limit of " + ToString(limit) + " bytes");
    }

    try {
        TStringBuf inStream(post.AsCharPtr(), post.Length());
        IncomingMessage = JSON_MAP;
        ReadJsonFastTree(inStream, &IncomingMessage, true);
        return true;
    } catch (...) {
        RETURN_ERROR("An error occurred while parsing json: " + CurrentExceptionMessage());
    }
    return false;
}
