package speiger.src.coreengine.utils.collections.managers.dynamic;

public class DataSlot implements Comparable<DataSlot>
{
	DataSlot previous;
	DataSlot next;
	int dataIndex = -1;
	int byteOffset;
	byte[] value;
	
	public DataSlot set(DataSlot previous, int dataIndex, byte[] value)
	{
		this.previous = previous;
		byteOffset = previous == null ? 0 : previous.getNextByteOffset();
		this.dataIndex = dataIndex;
		this.value = value;
		if(this.previous != null) this.previous.next = this;
		return this;
	}
	
	public DataSlot setData(int dataIndex, byte[] value)
	{
		this.dataIndex = dataIndex;
		this.value = value;
		return this;
	}
	
	@Override
	public int compareTo(DataSlot o)
	{
		return Integer.compare(byteOffset, o.byteOffset);
	}
	
	public int getNextByteOffset()
	{
		return byteOffset + (value == null ? 0 : value.length);
	}
	
	public int getUsedBytes()
	{
		return next == null ? (value == null ? 0 : value.length) : next.byteOffset - byteOffset;
	}
	
	public int getFreeBytes()
	{
		return next == null ? Integer.MAX_VALUE : next.byteOffset - byteOffset;
	}
	
	public void clear()
	{
		dataIndex = -1;
		value = null;
		if(previous != null)
		{
			previous.next = null;
			previous = null;
		}
		if(next != null)
		{
			next.previous = null;
			next = null;
		}
	}
}
