using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using skyscraper5.Mpeg2;
using skyscraper5.Skyscraper.IO;
using skyscraper5.Skyscraper.Plugins;

namespace skyscraper8.InteractionChannel.Model2.Descriptors
{
	[SkyscraperPlugin]
	[TsDescriptor(0xb9,"TIM")]
	public class _0xb9_LogonResponseDescriptor : TsDescriptor
	{
		public _0xb9_LogonResponseDescriptor(byte[] buffer)
		{
			MemoryStream ms = new MemoryStream(buffer, false);
			byte byteA = ms.ReadUInt8();
			KeepIdentifiersAfterLogoff = (byteA & 0x40) != 0;
			PowerControlMode = (EirpControlModes)((byteA & 0x30) >> 4);
			RcstAccessStatus = (byteA & 0x0f);
			GroupId = ms.ReadUInt8();
			LogonId = ms.ReadUInt16BE();
			LowestAssignmentId = ms.ReadUInt24BE();

			byte byteB = ms.ReadUInt8();
			AssignmentIdCount = (byteB & 0xf0) >> 4;
			int unicastMac24Count = (byteB & 0x0f);
			UnicastMac24s = new Mac24[unicastMac24Count];
			for (int i = 0; i < unicastMac24Count; i++)
			{
				Mac24 child = new Mac24();
				UnicastMac24s[i] = child;
				child.Mac24PrefixSize = ms.ReadUInt8() & 0x1f;
				child.UnicastMac24 = ms.ReadBytes(3);
				byte byteC = ms.ReadUInt8();
				child.MulticastMappingMethod = (byteC & 0x40) != 0;
				child.MulticastIpVersionIndicatorPresence = (byteC & 0x20) != 0;
				child.MulticastSynthesisFieldSize = (byteC & 0x1f);
			}

			DefaultSvnNumber = ms.ReadUInt16BE();
			byte reserved = ms.ReadUInt8();
			Valid = true;
		}

		public ushort DefaultSvnNumber { get; set; }

		public Mac24[] UnicastMac24s { get; private set; }
		public class Mac24
		{
			public int Mac24PrefixSize { get; set; }
			public byte[] UnicastMac24 { get; set; }
			public bool MulticastMappingMethod { get; set; }
			public bool MulticastIpVersionIndicatorPresence { get; set; }
			public int MulticastSynthesisFieldSize { get; set; }
		}
		public int AssignmentIdCount { get; set; }

		public uint LowestAssignmentId { get; set; }

		public ushort LogonId { get; set; }

		public byte GroupId { get; set; }

		public int RcstAccessStatus { get; set; }

		public EirpControlModes PowerControlMode { get; set; }

		public bool KeepIdentifiersAfterLogoff { get; set; }

		public enum EirpControlModes
		{
			ConstantEirp = 0,
			AutonomousEirp = 1,
			ConstantPowerSpectrum = 2,
		}

		public override string ToString()
		{
			return $"Logon Response for {nameof(GroupId)}: {GroupId}, {nameof(LogonId)}: {LogonId}";
		}
	}
}
