using Newtonsoft.Json;
using skyscraper5.Skyscraper.IO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace skyscraper5.DNS.Protocol.ResourceRecords.Records
{
	internal class HttpsSpecificServiceEndspointsRecord : BaseResourceRecord, SimpleDnsRecord
	{
		public HttpsSpecificServiceEndspointsRecord(ResourceRecord record, byte[] message, int dataOffset)
			: base(record)
		{
			if (BitConverter.IsLittleEndian)
				(Data[0], Data[1]) = (Data[1], Data[0]);
			SvcPriority = BitConverter.ToUInt16(Data, 0);

			int nextOffset = 2;
			TargetName = Domain.FromArray(Data, 2, out nextOffset);

			MemoryStream ms = new MemoryStream(Data, false);
			ms.Position = nextOffset;
			while (ms.GetAvailableBytes() > 2)
			{
				ushort key = ms.ReadUInt16BE();
				int valueLength = ms.ReadUInt16BE();
				if (valueLength > ms.GetAvailableBytes())
					return;
				byte[] value = ms.ReadBytes(valueLength);
				if (SvcParams == null)
					SvcParams = new List<KeyValuePair<ushort, byte[]>>();
				SvcParams.Add(new KeyValuePair<ushort, byte[]>(key, value));
			}
		}

		public ushort SvcPriority { get; }
		public Domain TargetName { get; }
		public List<KeyValuePair<ushort,byte[]>> SvcParams { get; }

		public string GetDataAsString()
		{
			dynamic child = new
			{
				SvcPriority = SvcPriority,
				TargetName = TargetName.ToString(),
				SvcParams = SvcParams
			};
			string result = JsonConvert.SerializeObject(child);
			return result;
		}
	}
}
