#include "intervals_enumeration.h"

void NSaas::UrlEnumeration::EnumerateIntervals(NSearchMapParser::TShardIndex shardIndex, const TShardIntervals& sortedIntervals, IShardIntervalCallback& callback) {
    size_t intervalIndex = shardIndex * sortedIntervals.size() / (sortedIntervals.back().GetMax() - sortedIntervals.front().GetMin());
    auto first = sortedIntervals.begin();
    auto last = sortedIntervals.end();
    if (intervalIndex < sortedIntervals.size()) {
        if (shardIndex < sortedIntervals[intervalIndex].GetMin()) {
            last = first + intervalIndex;
        } else if (shardIndex > sortedIntervals[intervalIndex].GetMax()) {
            first += intervalIndex + 1;
        } else {
            callback.OnShardInterval(intervalIndex);
            return;
        }
    }
    NSearchMapParser::TShardsInterval interval(shardIndex, shardIndex);
    auto it = std::lower_bound(first, last, interval);
    if (it != last && it->Check(shardIndex)) {
        callback.OnShardInterval(std::distance(sortedIntervals.begin(), it));
    }
}