#include "yt_blob.h"

#include <mapreduce/yt/interface/cypress.h>


TYTBlob::TYTBlob(const NYT::TNode& node, EYTBlobFormat format) {
    SetShardMin(node.ChildAsInt64("shard_min"));
    SetShardMax(node.ChildAsInt64("shard_max"));

    Data.SetPartIndex(node.ChildAsInt64("part_index"));
    Data.SetData(node.ChildAsString("data"));
    Data.SetSegmentId(node.ChildAsInt64("segment_id"));

    if (format == EYTBlobFormat::Old) {
        Data.SetName(node.ChildAsString("name"));
        Data.SetDataLength(node.ChildAsInt64("data_length"));
    } else {
        Data.SetName(node.ChildAsString("filename"));
        Data.SetDataLength(node.ChildAsInt64("data_size"));
    }
}


TYTBlob::TYTBlob(const NSaas::TYTNewBlobBase& blob) {
    if (blob.HasShardMin()) {
        Data.SetShardMin(blob.GetShardMin());
    }
    if (blob.HasShardMax()) {
        Data.SetShardMax(blob.GetShardMax());
    }
    if (blob.HasFilename()) {
        Data.SetName(blob.GetFilename());
    }
    if (blob.HasPartIndex()) {
        Data.SetPartIndex(blob.GetPartIndex());
    }
    if (blob.HasData()) {
        Data.SetData(blob.GetData());
    }
    if (blob.HasDataSize()) {
        Data.SetDataLength(blob.GetDataSize());
    }
    if (blob.HasSegmentId()) {
        Data.SetSegmentId(blob.GetSegmentId());
    }
}

TYTBlob::operator NSaas::TYTNewBlobBase() const {
    NSaas::TYTNewBlobBase proto;
    if (Data.HasShardMin()) {
        proto.SetShardMin(Data.GetShardMin());
    }
    if (Data.HasShardMax()) {
        proto.SetShardMax(Data.GetShardMax());
    }
    if (Data.HasName()) {
        proto.SetFilename(Data.GetName());
    }
    if (Data.HasPartIndex()) {
        proto.SetPartIndex(Data.GetPartIndex());
    }
    if (Data.HasData()) {
        proto.SetData(Data.GetData());
    }
    if (Data.HasDataLength()) {
        proto.SetDataSize(Data.GetDataLength());
    }
    if (Data.HasSegmentId()) {
        proto.SetSegmentId(Data.GetSegmentId());
    }
    return proto;
}

EYTBlobFormat GetBlobFormatFromAttrs(NYT::IClientBasePtr client, const NYT::TRichYPath& tablePath) {
    TString path = client->CanonizeYPath(tablePath).Path_;
    EYTBlobFormat blobFormat = EYTBlobFormat::Old;
    TString formatAttribute = path + "/@blob_format";
    if (client->Exists(formatAttribute)) {
        TryFromString<EYTBlobFormat>(client->Get(formatAttribute).AsString(), blobFormat);
    }
    return blobFormat;
}
