package speiger.src.coreengine.utils.io.dataTag.array;

import java.io.IOException;
import java.util.Arrays;

import speiger.src.coreengine.utils.io.dataTag.DataTag;
import speiger.src.coreengine.utils.io.dataTag.compression.DataTagLimiter;
import speiger.src.coreengine.utils.io.dataTag.compression.TagCompressor;
import speiger.src.coreengine.utils.io.dataTag.compression.TagDecompressor;
import speiger.src.coreengine.utils.io.streams.ExtendedDataInput;
import speiger.src.coreengine.utils.io.streams.ExtendedDataOutput;

public class IntArrayTag implements DataTag
{
	int[] value;
	
	public IntArrayTag()
	{
		this(new int[0]);
	}
	
	public IntArrayTag(int[] data)
	{
		value = data;
	}
	
	@Override
	public int getId()
	{
		return 12;
	}
	
	@Override
	public String getTypeName()
	{
		return "Integer Array";
	}
	
	@Override
	public long countBytes(long input)
	{
		return input + 4L + (value.length * 4L);
	}
	
	@Override
	public void write(ExtendedDataOutput output, TagCompressor compressor) throws IOException
	{
		output.writeVarInt(value.length);
		for(int i = 0,m=value.length;i<m;i++)
		{
			output.writeInt(value[i]);
		}
	}
	
	@Override
	public void read(ExtendedDataInput input, TagDecompressor decompressor, int depthLimit, DataTagLimiter limiter) throws IOException
	{
		int size = input.readVarInt();
		limiter.countBytes((size * 4) + 4);
		value = new int[size];
		for(int i = 0;i<size;i++)
		{
			value[i] = input.readInt();
		}
	}
	
	@Override
	public IntArrayTag copy()
	{
		return new IntArrayTag(Arrays.copyOf(value, value.length));
	}
	
	public int[] get()
	{
		return value;
	}
	
	@Override
	public int hashCode()
	{
		return Arrays.hashCode(value);
	}
	
	@Override
	public boolean equals(Object obj)
	{
		return obj instanceof IntArrayTag && Arrays.equals(((IntArrayTag)obj).value, value);
	}
	
	@Override
	public String toString()
	{
		StringBuilder stringbuilder = new StringBuilder("[I;");
		for(int i = 0, m = value.length;i < m;++i)
		{
			if(i != 0)
			{
				stringbuilder.append(',');
			}
			stringbuilder.append(value[i]);
		}
		return stringbuilder.append(']').toString();
	}
	
	@Override
	public String prettyPrint(String indent, int depth)
	{
		StringBuilder builder = new StringBuilder("[").append(TYPE_HIGHLIGHT).append("I").append(RESET_HIGHLIGHT).append(";");
		for(int i = 0, m = value.length;i < m;++i)
		{
			if(i != 0)
			{
				builder.append(',');
			}
			builder.append(NUMBER_HIGHLIGHT).append(value[i]).append(RESET_HIGHLIGHT);
		}
		return builder.append(']').toString();
	}
}
