package speiger.src.coreengine.rendering.guiOld.components.window.color;

import java.util.BitSet;

import speiger.src.coreengine.math.ArrayUtil;

public class ColorPool
{
	int[] colors;
	BitSet locked;
	
	public ColorPool(int size)
	{
		colors = ArrayUtil.fill(new int[size], -1);
		locked = new BitSet(size);
	}
	
	public void addColor(int color)
	{
		int index = colors.length;
		boolean lock = false;
		for(int i = 0,m=colors.length;i<m;i++)
		{
			if(colors[i] == color)
			{
				index = i + 1;
				lock = isLocked(i);
				break;
			}
		}
		for(int i = index - 1;i>0;i--)
		{
			if(isLocked(i) && (index == colors.length || i != (index - 1)))
			{
				continue;
			}
			colors[i] = colors[i-1];
			locked.set(i, locked.get(i-1));
			locked.clear(i-1);
		}
		colors[0] = color;
		locked.set(0, lock);
	}
	
	public void removeColor(int index)
	{
		colors[index] = -1;
	}
	
	public int getColor(int index)
	{
		return colors[index];
	}
	
	public void toggleLock(int index)
	{
		locked.set(index, !locked.get(index));
	}
	
	public void lockIndex(int index)
	{
		locked.set(index);
	}
	
	public void unlockIndex(int index)
	{
		locked.clear(index);
	}
	
	public boolean isLocked(int index)
	{
		return locked.get(index);
	}
	
	public int[] getColors()
	{
		return colors.clone();
	}
	
	public long[] getLocked()
	{
		return locked.toLongArray();
	}
	
	public void setData(int[] array, long[] locked)
	{
		System.arraycopy(array, 0, colors, 0, Math.min(array.length, colors.length));
		this.locked = BitSet.valueOf(locked);
	}
	
	public void clear()
	{
		ArrayUtil.fill(colors, -1);
		locked.clear();
	}
	
	public int size()
	{
		return colors.length;
	}
}
