/*
 * 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.esp.eo.sdk;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Iterator;

/**
 * Iterator for EOs which provides a filtering mechanic.
 *
 * @author Alex Leigh
 */
public class EOFilteringIterator implements Iterator<EO> {
    private static final Logger logger = LoggerFactory.getLogger(EOFilteringIterator.class);
    private final Iterator<EO> parent;
    private final String apiType;
    private EO current = null;

    /**
     * Create a new <code>EOFilteringIterator</code> based on the given iterator. This iterator will
     * only return EOs from the loop which claim to be compatible with the given type according to
     * each EO's <code>isType()</code> method.
     * <p>
     * The <code>EOFilteringIterator</code> will not recurse into children which might be found within the
     * <code>EOs</code>.
     *
     * @param parent
     * @param apiType
     */
    public EOFilteringIterator(Iterator<EO> parent, String apiType) {
        logger.debug("Filtering iterator created: {}", apiType);
        this.parent = parent;
        this.apiType = apiType;
        feed();
    }

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

    @Override
    public EO next() {
        EO eo = current;
        feed();
        return eo;
    }

    private void feed() {
        while (true) {
            if (!parent.hasNext()) {
                logger.debug("Parent has no next().");
                current = null;
                return;
            }

            current = parent.next();
            logger.debug("Loaded current: {}", current);
            if (current.isType(apiType)) return;
        }
    }
}
