#include "proto_table_writer.h"
#include <mapreduce/yt/io/proto_helpers.h>

namespace NRTYT {

void TProtoWriter::AddRow(const NYT::Message& row, size_t tableIndex) {
    Y_ENSURE(tableIndex < GetTableCount(), "While TProtoWriter::AddRow: table index " << tableIndex << " out of bounds (0, " << GetTableCount() << ")");

    NYT::ValidateProtoDescriptor(row, tableIndex, Descriptors, false);

    Y_VERIFY(row.GetReflection()->GetUnknownFields(row).empty(),
        "Message has unknown fields. This probably means bug in client code.\n"
        "Message: %s", row.DebugString().data());

    TString serializedProto;
    if (!row.SerializeToString(&serializedProto)) {
        ythrow yexception() << "Failed while serializing protobuf to string";
    }
    TBlob blob = TBlob::FromString(serializedProto);
    Archives[tableIndex]->PutDocument(blob, RowIds[tableIndex]++);
}
void TProtoWriter::AddRow(NYT::Message&& row, size_t tableIndex) {
    AddRow(row, tableIndex);
}

size_t TProtoWriter::GetTableCount() const {
    return ArchivePaths.size();
}
void TProtoWriter::FinishTable(size_t tableIndex) {
    Y_ENSURE(tableIndex < GetTableCount(), "While TProtoWriter::FinishTable: table index " << tableIndex << " out of bounds (0, " << GetTableCount() << ")");
    Archives[tableIndex]->Flush();
}

} // namespace NRTYT
