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

/**
 * Determines if two items should be combined
 */
public class QMungerImpl implements QMunger
{
	public String mungeables="";
	public boolean[] kndx=null;
	public boolean[] mndx=null;
	public boolean[] dndx=null;

	/**
	 * Returns the combined item, or null if they can not be combined.
	 */
	public List combine(List keyList, QIndexedComparableList icl)
	{
		int i,s;
		s=keyList.size();
		if (kndx==null)
		{
			kndx=new boolean[s];
			mndx=new boolean[s];
			dndx=new boolean[s];
			for (i=0;i<s;++i)
			{
				char x=mungeables.charAt(i);
				kndx[i]=x=='k';
				mndx[i]=x=='m';
				dndx[i]=x=='d';
			}
		}
		for (i=0;i<s;++i)
		{
			if (kndx[i])
			{
				Object k0=keyList.get(i);
				Object k1=icl.keyList.get(i);
				if (!k0.equals(k1))
				{
					return null;
				}
			}
		}
		for (i=0;i<s;++i)
		{
			if (mndx[i])
			{
				Object k0=keyList.get(i);
				Object k1=icl.keyList.get(i);
				if (!k0.equals(k1))
					keyList.set(i,null);
			}
		}
		return keyList;
	}

	public List finalize(List keyList, int[] order)
	{

		int i,s;
		List list=new ArrayList();
		s=keyList.size();
		if (kndx==null)
		{
			kndx=new boolean[s];
			mndx=new boolean[s];
			dndx=new boolean[s];
			for (i=0;i<s;++i)
			{

				char x=mungeables.charAt(i);
				kndx[i]=x=='k';
				mndx[i]=x=='m';
				dndx[i]=x=='d';
			}
		}
		for (i=s-1;i>-1;--i)
		{

			int j=order[i];
			if (!dndx[j])
				list.add(0,keyList.get(j));
		}
		return list;
	}

	public void fixOrder(int[] order)
	{
		while(fixOrder1(order))
		{
		}
	}

	boolean fixOrder1(int[] order)
	{
		int i,j,s;
		s=order.length;
		for (i=0;i<s;++i)
		{
			char x=mungeables.charAt(order[i]);
			if (x=='d')
				for (j=i+1;j<s;++j)
				{
					char y=mungeables.charAt(order[j]);
					if (y=='k')
					{
						int t=order[j-1];
						order[j-1]=order[j];
						order[j]=t;
						return true;
					}
				}
		}
		return false;
	}
}