/*
 * Copyright (c) 2004-2017, by Alex Leigh.
 * All rights reserved.
 *
 * THIS IS UNPUBLISHED PROPRIETARY SOURCE CODE
 * The copyright notice above does not evidence any
 * actual or intended publication of such source code.
 */

package lc.mecha.fabric;

import java.util.Iterator;

/**
 * Iterator which can perform subscription key matching.
 * <p>
 * MTS: Unsafe
 *
 * @author Alex Leigh
 */
public class MatchingIterator<E> implements Iterator<MessageSubscription<E>> {
    private final Iterator<MessageSubscription<E>> it;
    private final String symbol;
    private MessageSubscription<E> nextValue;

    public MatchingIterator(final Iterator<MessageSubscription<E>> rawIterator, final String symbol) {
        this.it = rawIterator;
        this.symbol = symbol;
        advance();
    }


    @Override
    public boolean hasNext() {
        return nextValue != null;
    }

    @Override
    public MessageSubscription<E> next() {
        final MessageSubscription<E> ret = nextValue;
        advance();
        return ret;
    }

    /**
     * Advance the iterator until the next matching value is discovered.
     */
    private void advance() {
        while (true) {
            if (!it.hasNext()) {
                nextValue = null;
                return;
            }

            nextValue = it.next();
            if (nextValue == null || nextValue.matches(symbol)) {
                return;
            }
        }
    }
}