#pragma once

#include <maps/wikimap/mapspro/services/mrc/libs/yt/include/serialization.h>

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

#include <iterator>

namespace maps::mrc::yt {

template<typename Iterator>
void saveToTable(
        NYT::IIOClient& client,
        const NYT::TRichYPath& path,
        Iterator begin,
        Iterator end)
{
    const auto writer = client.CreateTableWriter<NYT::TNode>(path);

    std::for_each(
        begin, end,
        [&writer](const auto& entity) {
            writer->AddRow(serialize(entity));
        }
    );
}

template<typename Container>
void saveToTable(
        NYT::IIOClient& client,
        const NYT::TRichYPath& path,
        const Container& container)
{
    saveToTable(client, path, container.begin(), container.end());
}

template<typename T, typename OutputIterator>
void loadFromTable(NYT::IIOClient& client, const NYT::TRichYPath& path, OutputIterator it)
{
    for (auto reader = client.CreateTableReader<NYT::TNode>(path); reader->IsValid(); reader->Next()) {
        *it = deserialize<T>(reader->GetRow());
        ++it;
    }
}

template<typename Container>
Container loadFromTable(NYT::IIOClient& client, const NYT::TRichYPath& path)
{
    using T = typename Container::value_type;

    Container container;
    loadFromTable<T>(client, path, std::back_inserter(container));
    return container;
}

} // maps::mrc::yt
