using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace skyscraper5.DNS.Protocol
{
	public class CharacterString
	{
		public static IList<CharacterString> GetAllFromArray(byte[] message, int offset)
		{
			return GetAllFromArray(message, offset, out offset);
		}

		public static IList<CharacterString> GetAllFromArray(byte[] message, int offset, out int endOffset)
		{
			IList<CharacterString> characterStrings = new List<CharacterString>();

			while (offset < message.Length)
			{
				characterStrings.Add(CharacterString.FromArray(message, offset, out offset));
			}

			endOffset = offset;
			return characterStrings;
		}

		public static CharacterString FromArray(byte[] message, int offset, out int endOffset)
		{
			if (message.Length < 1)
			{
				throw new ArgumentException("Empty message");
			}

			byte len = message[offset++];
			byte[] data = new byte[len];
			Buffer.BlockCopy(message, offset, data, 0, len);
			endOffset = offset + len;
			return new CharacterString(data);
		}

		internal string ToUTF8()
		{
			return Encoding.UTF8.GetString(data);
		}

		public CharacterString(byte[] data)
		{
			if (data.Length > MAX_SIZE) Array.Resize(ref data, MAX_SIZE);
			this.data = data;
		}

		private const int MAX_SIZE = byte.MaxValue;
		private byte[] data;
	}
}
