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.dataTag.simple.StringTag;
import speiger.src.coreengine.utils.io.streams.ExtendedDataInput;
import speiger.src.coreengine.utils.io.streams.ExtendedDataOutput;

public class StringArrayTag implements DataTag
{
	String[] value;
	
	public StringArrayTag()
	{
		value = new String[0];
	}
	
	public StringArrayTag(String[] data)
	{
		value = data;
		for(int i = 0,m=data.length;i<m;i++)
		{
			if(value[i] == null)
			{
				value[i] = "";
			}
		}
	}
	
	@Override
	public int getId()
	{
		return 16;
	}
	
	@Override
	public String getTypeName()
	{
		return "String Array";
	}
	
	@Override
	public long countBytes(long input)
	{
		input += 4L;
		for(int i = 0,m=value.length;i<m;i++)
		{
			input += value[i].length() * 2L;
		}
		return input;
	}
	
	@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.writeString(value[i]);
		}
	}
	
	@Override
	public void read(ExtendedDataInput input, TagDecompressor decompressor, int depthLimit, DataTagLimiter limiter) throws IOException
	{
		int size = input.readVarInt();
		limiter.countBytes(4 + (size * 4));
		value = new String[size];
		for(int i = 0;i<size;i++)
		{
			value[i] = input.readString();
			limiter.countBytes(value[i].length() * 2);
		}
	}
	
	@Override
	public StringArrayTag copy()
	{
		return new StringArrayTag(Arrays.copyOf(value, value.length));
	}
	
	public String[] get()
	{
		return value;
	}
	
	@Override
	public int hashCode()
	{
		return Arrays.hashCode(value);
	}
	
	@Override
	public boolean equals(Object obj)
	{
		return obj instanceof StringArrayTag && Arrays.equals(((StringArrayTag)obj).value, value);
	}
	
	@Override
	public String toString()
	{
		StringBuilder stringbuilder = new StringBuilder("[A;");
		for(int i = 0, m = value.length;i < m;++i)
		{
			if(i != 0)
			{
				stringbuilder.append(',');
			}
			stringbuilder.append(StringTag.quoteAndEscape(value[i]));
		}
		return stringbuilder.append(']').toString();
	}
	
	@Override
	public String prettyPrint(String indent, int depth)
	{
		StringBuilder builder = new StringBuilder("[").append(TYPE_HIGHLIGHT).append("A").append(RESET_HIGHLIGHT).append(";");
		for(int i = 0, m = value.length;i < m;++i)
		{
			if(i != 0)
			{
				builder.append(',');
			}
			StringBuilder subBuilder = StringTag.quoteAndEscapeBuilder(value[i]).insert(1, STRING_HIGHLIGHT);
			builder.append(subBuilder.insert(subBuilder.length() - 1, RESET_HIGHLIGHT));
		}
		return builder.append(']').toString();
	}
}
