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

namespace skyscraper5.Dvb.Descriptors
{
	[SkyscraperPlugin]
	[TsDescriptor(0x41,"NIT","BAT")]
    [BannedTable("PMT","TSDT","EIT")]
    public class ServiceListDescriptor : TsDescriptor
    {
        public ServiceListDescriptor(byte[] buffer)
        {
            if (buffer == null)
                return;
            if (buffer.Length % 3 != 0)
                return;

            Services = new Service[buffer.Length / 3];
            for (int i = 0; i < buffer.Length; i += 3)
            {
                (buffer[i], buffer[i + 1]) = (buffer[i + 1], buffer[i]);
                Services[i / 3] = new Service(BitConverter.ToUInt16(buffer, i), (ServiceDescriptor.ServiceTypeCoding)buffer[i + 2]);
            }

            Valid = true;
        }
        
        public Service[] Services { get; private set; }


        public struct Service
        {
            public ushort ServiceId { get; }
            public ServiceDescriptor.ServiceTypeCoding ServiceType { get; }

            public Service(ushort serviceId, ServiceDescriptor.ServiceTypeCoding serviceType)
            {
                ServiceId = serviceId;
                ServiceType = serviceType;
            }

            public bool Equals(Service other)
            {
                return ServiceId == other.ServiceId;
            }

            public override bool Equals(object obj)
            {
                return obj is Service other && Equals(other);
            }

            public override int GetHashCode()
            {
                return ServiceId.GetHashCode();
            }
        }
    }
}
