#include "intersect_iterator.h"

TIntersectIterator::TIntersectIterator(const TVector<TTrigramIndexManager::TIterator::TPtr>& iterators)
    : InvalidIteratorsCount(0)
    , Iterators(iterators)
{
    for (auto& it : Iterators) {
        if (it->Valid()) {
            CurrentMax = it->GetPosition();
            break;
        }
    }
}

bool TIntersectIterator::Valid() const {
    return InvalidIteratorsCount != Iterators.size();
}

void TIntersectIterator::Next() {
    SUPERLONG max = CurrentMax + 1;
    do {
        CurrentMax = max;
        for (auto iter : Iterators) {
            if (iter->Valid()) {
                while (iter->Valid() && iter->GetPosition() < max) {
                    iter->Next();
                }
                if (iter->Valid()) {
                    max = Max(max, iter->GetPosition());
                } else {
                    ++InvalidIteratorsCount;
                }
            }
        }
    } while (max != CurrentMax);
}

SUPERLONG TIntersectIterator::GetPosition() const {
    return CurrentMax;
}
