#include "requester_utils.h"
#include "request_utils.h"
#include "request_context_utils.h"

#include <semaphore>

namespace NHttp::NUtils {
TExpected<TFullResponse, TError> Send(IRequester& requester, TRequest request, TInstant deadline) {
    auto context = requester.Send(std::move(request));
    TMaybe<TReadAllResult> out;
    std::binary_semaphore semaphore{0};
    ReadAll(*context, deadline, [&](auto result) {
        out = std::move(result);
        semaphore.release();
    });

    semaphore.acquire();
    if (out->IsError()) {
        return std::move(out->Error());
    }

    return std::move(out->Success().GetRef());
}

IResponseParser::TResult SendParsed(IRequester& requester, TRequest request, IResponseParser& parser, TInstant deadline) {
    auto context = requester.Send(std::move(request));

    TMaybe<IResponseParser::TResult> out;
    std::binary_semaphore semaphore{0};
    context->Read(parser, deadline, [&](auto result) {
        out = std::move(result);
        semaphore.release();
    });

    semaphore.acquire();
    if (out->IsError()) {
        return std::move(out->Error());
    }

    return std::move(out->Success());
}
}
