#include "json_parser.h"

#include <balancer/client/experimental/util/response_stream_utils.h>

#include <balancer/kernel/custom_io/stream.h>

namespace NHttp::NParsers {
void TJsonParser::Parse(NHttp::IResponseStream& stream, TInstant deadline, THandler callback) noexcept {
    NUtils::ReadAll(stream, deadline, [callback = std::move(callback)](NUtils::TReadAllResult result) {
        if (result.IsError()) {
            return callback(std::move(result.Error()));
        }

        NSrvKernel::TChunkInputStream stream{std::move(result.Success().GetRef().Body)};
        NJson::TJsonValue json;
        if (NJson::ReadJsonTree(&stream, &json, false)) {
            callback(std::any{std::move(json)});
        } else {
            callback(TError{"json parse failed"});
        }
    });
}

TJsonParser& JsonParser() {
    return *Singleton<TJsonParser>();
}
}
