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

namespace skyscraper8.InteractionChannel.Model2.Descriptors
{
	[SkyscraperPlugin]
	[TsDescriptor(0xc4,"TIM")]
	public class _0xc4_HigherLayersInitializeDescriptor : TsDescriptor
	{
		public _0xc4_HigherLayersInitializeDescriptor(byte[] buffer)
		{
			MemoryStream ms = new MemoryStream(buffer, false);
			int satL2ifCount = (ms.ReadUInt8() & 0x0f);
			Layer2Interfaces = new Layer2Interface[satL2ifCount];
			for (int i = 0; i < satL2ifCount; i++)
			{
				Layer2Interface child = new Layer2Interface();
				Layer2Interfaces[i] = child;
				child.Mac24 = ms.ReadBytes(3);
				child.Ipv4McAddress = new IPAddress(ms.ReadBytes(4));
				child.OfferStreamIpv4Adress = new IPAddress(ms.ReadBytes(4));
				child.OfferStreamPort = ms.ReadUInt16BE();
				child.HigherLayerPepSwitchOff = (ms.ReadUInt8() & 0x01) != 0;
			}

			Valid = true;
		}

		public Layer2Interface[] Layer2Interfaces { get; set; }

		public class Layer2Interface
		{
			public byte[] Mac24 { get; set; }
			public IPAddress Ipv4McAddress { get; set; }
			public IPAddress OfferStreamIpv4Adress { get; set; }
			public ushort OfferStreamPort { get; set; }
			public bool HigherLayerPepSwitchOff { get; set; }

			public string Mac24AsString => BitConverter.ToString(Mac24);

			protected bool Equals(Layer2Interface other)
			{
				return Mac24AsString.Equals(other.Mac24AsString) && Ipv4McAddress.Equals(other.Ipv4McAddress) && OfferStreamIpv4Adress.Equals(other.OfferStreamIpv4Adress) && OfferStreamPort == other.OfferStreamPort && HigherLayerPepSwitchOff == other.HigherLayerPepSwitchOff;
			}

			public override bool Equals(object? obj)
			{
				if (ReferenceEquals(null, obj)) return false;
				if (ReferenceEquals(this, obj)) return true;
				if (obj.GetType() != this.GetType()) return false;
				return Equals((Layer2Interface)obj);
			}

			public override int GetHashCode()
			{
				return HashCode.Combine(Mac24AsString, Ipv4McAddress, OfferStreamIpv4Adress, OfferStreamPort, HigherLayerPepSwitchOff);
			}
		}

		public override string ToString()
		{
			return String.Format("{0} Higher Layer Initalizations", Layer2Interfaces.Length);
		}
	}
}
