package com.jxml.quick.qmap;
import java.util.*;

/**
 * A fancy iterator.
 */
public class QIndexMap extends TreeMap implements QIndex
{
	List order=new ArrayList();
	public int[] ndx;
	public Map values;
	public QQualifier qualifier;
	public QMunger munger=null;
	public Iterator iterator=null;
	public List last=null;

	public QIndexMap(){}

	/**
	 * @param order a list of Integer objects.
	 */
	public QIndexMap(Map values, List order, QQualifier qualifier, QMunger munger)
	{
		this.order=order;
		this.qualifier=qualifier;
		this.values=values;
		this.munger=munger;
	}

	public void reset()
	{
		iterator=null;
	}

	public boolean hasNext()
	{
		if (iterator==null)
		{
			int i,s;
			s=order.size();
			ndx=new int[s];
			for (i=0;i<s;++i)
			{
				Integer in=(Integer)order.get(i);
				ndx[i]=in.intValue();
			}
			munger.fixOrder(ndx);

			clear();
			Set keySet=values.keySet();
			Iterator keyIterator=keySet.iterator();
			while (keyIterator.hasNext())
			{
				QIndexedComparableList icl=(QIndexedComparableList)keyIterator.next();
				if (qualifier.acceptable(icl))
					icl.copy(this);
			}
	
			keySet=keySet();
			iterator=keySet.iterator();
			if (iterator.hasNext())
				last=new ArrayList(((QIndexedComparableList)iterator.next()).keyList);
			else
				last=null;
		}
		return last!=null;
	}

	public List next()
	{

//		Set keySet=keySet();
//		iterator=keySet.iterator();
//		if (iterator.hasNext())
//			last=new ArrayList(((QIndexedComparableList)iterator.next()).keyList);


		List rv=last;
		while (iterator.hasNext())
		{
			QIndexedComparableList n=(QIndexedComparableList)iterator.next();
			last=munger.combine(rv,n);
			if (last==null)
			{
				last=n.keyList;
				return munger.finalize(rv,ndx);
			}
			rv=last;
		}
		last=null;
		return munger.finalize(rv,ndx);
	}

	public int index(int k)
	{
		if (ndx==null)
			return k;
		return ndx[k];
	}
}