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 ShortArrayTag implements DataTag
{
	short[] value;
	
	public ShortArrayTag()
	{
		this(new short[0]);
	}
	
	public ShortArrayTag(short[] data)
	{
		value = data;
	}
	
	@Override
	public int getId()
	{
		return 10;
	}
	
	@Override
	public String getTypeName()
	{
		return "Short Array";
	}
	
	@Override
	public long countBytes(long input)
	{
		return input + 4L + (value.length * 2L);
	}
	
	@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.writeShort(value[i]);
		}
	}
	
	@Override
	public void read(ExtendedDataInput input, TagDecompressor decompressor, int depthLimit, DataTagLimiter limiter) throws IOException
	{
		int size = input.readVarInt();
		limiter.countBytes(4 + (size * 2));
		value = new short[size];
		for(int i = 0;i<size;i++)
		{
			value[i] = input.readShort();
		}
	}
	
	@Override
	public ShortArrayTag copy()
	{
		return new ShortArrayTag(Arrays.copyOf(value, value.length));
	}
	
	public short[] get()
	{
		return value;
	}
	
	@Override
	public int hashCode()
	{
		return Arrays.hashCode(value);
	}
	
	@Override
	public boolean equals(Object obj)
	{
		return obj instanceof ShortArrayTag && Arrays.equals(((ShortArrayTag)obj).value, value);
	}
	
	@Override
	public String toString()
	{
		StringBuilder stringbuilder = new StringBuilder("[S;");
		for(int i = 0, m = value.length;i < m;++i)
		{
			if(i != 0)
			{
				stringbuilder.append(',');
			}
			stringbuilder.append(value[i]).append('s');
		}
		return stringbuilder.append(']').toString();
	}
	
	@Override
	public String prettyPrint(String indent, int depth)
	{
		StringBuilder builder = new StringBuilder("[").append(TYPE_HIGHLIGHT).append("S").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(TYPE_HIGHLIGHT).append('s').append(RESET_HIGHLIGHT);
		}
		return builder.append(']').toString();
	}
}
