package net.ranides.assira.collection;

import java.util.Iterator;
import java.util.NoSuchElementException;

/*
 *  @author Ranides Atterwim <ranides@gmail.com>
 *  @copyright Ranides Atterwim
 *  @license WTFPL
 *  @url http://ranides.net/projects/assira
 */

/**
 *
 * @author Ranides
 * @param <T>
 */
public abstract class FilterIterator<T> implements Iterator<T> {
    
    private final Iterator<? extends T> iterator;
    private T next;
    private boolean hasNext;
    
    public abstract boolean accept(T value);

    public FilterIterator(Iterator<? extends T> iterator) {
        this.iterator = iterator;
        nextMatch();
    }

    @Override
    public boolean hasNext() {
        return hasNext;
    }

    @Override
    public T next() {
        if (!hasNext) {
            throw new NoSuchElementException();
        }
        return nextMatch();
    }

    private T nextMatch() {
        T last = next;

        while (iterator.hasNext()) {
            T value = iterator.next();
            if (accept(value)) {
                hasNext = true;
                next = value;
                return last;
            }
        }

        hasNext = false;
        return last;
    }

    @Override
    public void remove() {
        iterator.remove();
    }
    
}
