#pragma once

#include "../balancer_client.h"

#include <balancer/client/experimental/base/timeout_error.h>

#include <balancer/client/experimental/base/response_stream.h>

#include <balancer/kernel/coro/waked.h>

#include <util/generic/queue.h>
#include <util/system/mutex.h>

namespace NHttp::NRequesters {
class TBalancerClient::TResponseStream final: public IResponseStream {
  public:
    explicit TResponseStream(TWorker& worker);

    void Read(size_t sizeLimit, bool peek, TInstant deadline, TReadHandler callback) noexcept override;

    TReadResult Wait(size_t sizeLimit, bool peek, TInstant deadline);

    void PushData(TResponseFrame frame) noexcept;

    void Finish();

    void Error(TError error);

  private:
    TWorker& Worker_;
    TContSimpleEvent Event_;
    TQueue<TResponseFrame> Results_;
    TMaybe<TError> Error_;
    bool Finished_ = false;
    std::unique_ptr<TWorker::TCoroutine> ReadCoro_;
    std::unique_ptr<TWorker::TCoroutine> CallbackCoro_;
};
}
