import java.util.*;


/**
 * Iterate over a collection of anagrams
 * 
 * @author rcd
 */
public class Iterator implements java.util.Iterator
{
    private java.util.Iterator myIterator;
    private Set myAnagram;
    private int myMinNeeded;


    /**
     * Construct iterator pointing to beginning of set of anagrams
     */
    public Iterator (Map anagrams)
    {
        this(anagrams, 2);
    }

    /**
     * Construct iterator pointing to beginning of set of anagrams
     */
    public Iterator (Map anagrams, int minNeeded)
    {
        myIterator = anagrams.values().iterator();
        myMinNeeded = minNeeded;
        myAnagram = getNextAnagram();
    }

    /**
     * Returns true if the iteration has more elements.
     * @see java.util.Iterator#hasNext()
     */
    public boolean hasNext ()
    {
        return (myAnagram != null);
    }

    /**
     * Returns the next element in the iteration.
     * @see java.util.Iterator#next()
     */
    public Object next ()
    {
        if (hasNext())
        {
            Set current = myAnagram;
            myAnagram = getNextAnagram();
            return current;
        }
        else
        {
            throw new NoSuchElementException();
        }
    }
    
    /**
     * Not implemented, throws UnsupportedOperationException
     * @see UnsupportedOperationException
     */
    public void remove ()
    {
        throw new UnsupportedOperationException();
    }
    

    private Set getNextAnagram ()
    {
        Set result = null;

        while (myIterator.hasNext())
        {
            result = (Set)myIterator.next();
            if (isAnagram(result))
            {
                return result;
            }
        }

        return null;
    }

    private boolean isAnagram (Set possible)
    {
        return (possible.size() >= myMinNeeded);
    }
}
