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
{
	public class ResourceRecordSignatureRecord : BaseResourceRecord, SimpleDnsRecord
	{
		public ResourceRecordSignatureRecord(IResourceRecord record, byte[] message, int dataOffset)
			: base(record)
		{
			MemoryStream ms = new MemoryStream(Data, false);
			TypeCovered = ms.ReadUInt16BE();
			Algorithm = (AlgorithmEnum)ms.ReadUInt8();
			Labels = ms.ReadUInt8();
			OriginalTtl = new TimeSpan(0, 0, (int)ms.ReadUInt32BE());

			SignatureExpiration = ((long)ms.ReadUInt32BE()).ToUnixTime();
			SignatureInception = ((long)ms.ReadUInt32BE()).ToUnixTime();
			KeyTag = ms.ReadUInt16BE();

			int newPos = 0;
			SignersName = Domain.FromArray(Data, (int)ms.Position, out newPos);
			ms.Position = newPos;

			Signature = ms.ReadBytes(ms.GetAvailableBytes());
		}

		public ushort TypeCovered { get; }

		public AlgorithmEnum Algorithm { get; }
		public byte Labels { get; }
		public TimeSpan OriginalTtl { get; }
		public DateTime SignatureExpiration { get; }
		public DateTime SignatureInception { get; }
		public ushort KeyTag { get; }
		public Domain SignersName { get; private set; }
		public byte[] Signature { get; }

		public string GetDataAsString()
		{
			dynamic child = new
			{
				TypeCovered = TypeCovered,
				Algorithm = Algorithm,
				Labels = Labels,
				OriginalTtl = OriginalTtl,
				SignatureExpiration = SignatureExpiration,
				SignatureInception = SignatureInception,
				KeyTag = KeyTag,
				SignersName = SignersName,
				Signature = Signature
			};
			string result = JsonConvert.SerializeObject(child);
			return result;
		}
	}

	public enum AlgorithmEnum : byte
	{
		DSA_SHA1 = 3,
		RSA_SHA1 = 5,
		DSA_SHA1_NSEC3 = 6,
		RSA_SHA1_NSEC3 = 7,
		RSA_SHA256 = 8,
		RSA_SHA512 = 10,
		GOST_R_34102001 = 12,
		ECDSA_CURVE_P256_SHA256 = 13,
		ECDSA_CURVE_P384_SHA384 = 14,
		ED25519 = 15,
		ED448 = 16
	}
}
