#include "channel_input.h"

namespace NHttp::NRequesters {
TChannelInput::TChannelInput(NSrvKernel::TU2WChannel<NSrvKernel::TChunkList>& channel, TContExecutor* executor)
    : Channel_{channel}
    , Executor_{executor}
{}

NSrvKernel::TError TChannelInput::DoRecv(NSrvKernel::TChunkList& lst, TInstant deadline) noexcept {
    lst = {};
    if (Eof_) {
        return {};
    }

    NSrvKernel::EChannelStatus status = Channel_.Receive(lst, deadline, Executor_->Running(), NSrvKernel::ThreadLocalEventWaker().Get());
    switch (status) {
        case NSrvKernel::EChannelStatus::Canceled:
            return Y_MAKE_ERROR(TSystemError{ECANCELED});
        case NSrvKernel::EChannelStatus::TimedOut:
            return Y_MAKE_ERROR(TSystemError{ETIMEDOUT});
        case NSrvKernel::EChannelStatus::Success:
            if (lst.Empty()) {
                Eof_ = true;
            }
            return {};
    }
}
}
