#include "yt_chunked_output.h"
#include <saas/protos/yt.pb.h>

#include <util/generic/string.h>
#include <util/stream/hex.h>
#include <util/string/builder.h>

void TYTChunkedOutputBase::DoWriteChunk(const void* buf, size_t len, ui32 chunkId, const TString& name) {
    TYTBlob row;
    row.SetShardId(ShardId);

    auto& blobRef = row.GetBlobRef();
    if (name) {
        blobRef.SetName(name);
    }
    blobRef.SetSegmentId(SegmentId);
    blobRef.SetPartIndex(chunkId);
    blobRef.SetData(TString(static_cast<const char *>(buf), len));
    blobRef.SetDataLength(len);
    if (Format == EYTBlobFormat::Old) {
        TableWriter->AddRow<NSaas::TYTBlobBase>(static_cast<NSaas::TYTBlobBase>(row), TableIndex);
    } else {
        TableWriter->AddRow<NSaas::TYTNewBlobBase>(static_cast<NSaas::TYTNewBlobBase>(row), TableIndex);
    }
}

void TTextChunkedOutputBase::DoWriteChunk(const void* buf, size_t len, ui32 chunkId, const TString& name) {
    TStringBuilder s;
    s << name << '\t' << chunkId << '\t' << len << '\t';
    if (Hex) {
        HexEncode(buf, len, s.Out);
    } else {
        s.Out.Write(buf, len);
    }
    s << Endl;
    *Slave << s;
}

TYTCommonChunkedOutput::TConstructionContext TYTCommonChunkedOutput::CommonContext;
TRWMutex TYTCommonChunkedOutput::CommonContextMutex;
