/*
   Copyright 2007 Attila Szegedi

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

package org.dynalang.mop.impl;

import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Set;

class CompositeUniqueIterator<T> implements Iterator<T> {
    private final Set<Object> seenValues = new HashSet<Object>();
    private final LinkedList<Iterator<? extends T>> iterators = new LinkedList<Iterator<? extends T>>();
    private Iterator<? extends T> curr;
    private T next;
    private boolean needSeek = true;
    
    CompositeUniqueIterator(Iterator<? extends T> i1, Iterator<? extends T> i2) {
	assert i1 != null;
	assert i2 != null;
        curr = i1;
        iterators.add(i2);
    }

    void add(Iterator<? extends T> it) {
	assert it != null;
        iterators.add(it);
    }
    
    public boolean hasNext() {
        seekIfNeeded();
        return !needSeek;
    }
    public T next() {
        seekIfNeeded();
        needSeek = true;
        return next;
    }
    public void remove() {
        curr.remove();
    }
    
    private void seekIfNeeded() {
        if(needSeek) {
            for(;;) {
	            while(curr.hasNext()) {
	                next = curr.next();
		        if(seenValues.add(getKey(next))) {
			    needSeek = false;
			    return;
		        }
		    }
	            if(iterators.isEmpty()) {
	        	return;
	            }
                curr = iterators.removeFirst();
            }
        }
    }
    
    Object getKey(Object value) {
        return value;
    }
}