#include <maps/wikimap/mapspro/services/mrc/libs/fb/impl/utility.h>
#include <maps/wikimap/mapspro/services/mrc/libs/fb/include/photo_to_edge_pairs_reader.h>

#include <algorithm>

using namespace flatbuffers64;

namespace maps::mrc::fb {

PhotoToEdgePairsReader::PhotoToEdgePairsReader(const std::string& fromFile,
                                               EMappingMode mappingMode)
    : storage_{common::blobFromFile(fromFile, mappingMode)}
    , photoToEdgePairs_{GetRoot<PhotoToEdgePairs>(storage_.Data())}
{
}

std::string_view PhotoToEdgePairsReader::graphVersion() const
{
    return decode(*photoToEdgePairs_->graphVersion());
}

std::string_view PhotoToEdgePairsReader::mrcVersion() const
{
    return decode(*photoToEdgePairs_->mrcVersion());
}

TSchemaVersion PhotoToEdgePairsReader::schemaVersion() const
{
    return photoToEdgePairs_->schemaVersion();
}

size_t PhotoToEdgePairsReader::photoToEdgePairNumber() const
{
    return photoToEdgePairs_->photoToEdgePairs()->size();
}

const PhotoToEdgePair& PhotoToEdgePairsReader::photoToEdgePair(
    size_t offset) const
{
    REQUIRE(offset < photoToEdgePairNumber(), "out of photoToEdgePairs");
    return *photoToEdgePairs_->photoToEdgePairs()->Get(offset);
}

std::vector<PhotoToEdgePair> PhotoToEdgePairsReader::lookupByFeatureId(
    db::TId featureId) const
{
    auto searchValue = PhotoToEdgePair(featureId, {}, {}, {}, {});
    auto first = photoToEdgePairs_->photoToEdgePairs()->begin();
    auto last = photoToEdgePairs_->photoToEdgePairs()->end();
    auto [lowerBound, upperBound] = std::equal_range(
        first, last, &searchValue, [](const auto& lhs, const auto& rhs) {
            return lhs->featureId() < rhs->featureId();
        });
    auto result = std::vector<PhotoToEdgePair>{};
    std::for_each(lowerBound, upperBound, [&](const auto& item) {
        result.push_back(*item);
    });
    std::sort(
        result.begin(), result.end(), [](const auto& lhs, const auto& rhs) {
            return lhs.order() < rhs.order();
        });
    return result;
}

}  // namespace maps::mrc::fb
