using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using skyscraper5.Skyscraper.Net;

namespace skyscraper5.Dvb.DataBroadcasting.IntModel
{
    public class Target
    {
        //0x0f Target Ip Slash Descriptor
        public List<CidrSubnet> TargetIpSlashes { get; set; }

        //Was Loop empty?
        public bool AllReceivers { get; set; }

		public override bool Equals(object? obj)
		{
			return obj is Target target &&
				   EqualityComparer<List<CidrSubnet>>.Default.Equals(TargetIpSlashes, target.TargetIpSlashes) &&
				   AllReceivers == target.AllReceivers;
		}

		public override int GetHashCode()
		{
			return HashCode.Combine(TargetIpSlashes, AllReceivers);
		}

		public uint GenerateId()
		{
			if (AllReceivers)
				return uint.MaxValue;

			foreach(CidrSubnet subnet in  TargetIpSlashes)
			{
				IPAddress ipAddress = subnet.IpAddress;
				byte[] bytes = ipAddress.GetAddressBytes();
				return BitConverter.ToUInt32(bytes);
			}

			throw new NotImplementedException(String.Format("Failed to derive an identifier for a IP/MAC Notification target. This is a bug, the developers would need a sample of this TS to fix this."));
		}

		public override string ToString()
		{
			if (AllReceivers)
				return "<All Receivers>";

			StringBuilder sb = new StringBuilder();
			foreach (CidrSubnet subnet in TargetIpSlashes)
			{
				sb.Append(subnet.ToString());
				sb.Append(",");
			}
			return sb.ToString();
		}

        public object GenerateName()
        {
            throw new NotImplementedException();
        }
    }
}
