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

namespace skyscraper5.Dvb.Descriptors
{
	[SkyscraperPlugin]
	[TsDescriptor(0x66,"PMT")]
    [BannedTable("BAT")]
    public class DataBroadcastIdDescriptor : TsDescriptor
    {
        public DataBroadcastIdDescriptor(byte[] buffer)
        {
            MemoryStream ms = new MemoryStream(buffer, false);
            DataBroadcastId = ms.ReadUInt16BE();
            if (DataBroadcastId == 0x000b)
            {
                if (ms.GetAvailableBytes() == 0)
                    return;
                byte platformIdDataLength = ms.ReadUInt8();
                ParseIpMacNotification(ms.ReadBytes(platformIdDataLength));
            } 
            DataBroadcastSelector = ms.ReadBytes(ms.GetAvailableBytes());
        }

        public DataBroadcastIdDescriptor(ushort id)
        {
	        DataBroadcastId = id;
        }

        private void ParseIpMacNotification(byte[] buffer)
        {
            MemoryStream ms = new MemoryStream(buffer, false);
            IpMacNotificationInfo = new IpMacPlatform[buffer.Length / 5];
            for (int i = 0; i < IpMacNotificationInfo.Length; i++)
            {
                IpMacPlatform child = new IpMacPlatform();
                child.PlatformId = ms.ReadUInt24BE();
                child.ActionType = ms.ReadUInt8();
                byte readUInt8 = ms.ReadUInt8();
                child.IntVersioningFlag = (readUInt8 & 0x20) != 0;
                child.IntVersion = (readUInt8 & 0x1f);
                IpMacNotificationInfo[i] = child;
            }
        }

        public class IpMacPlatform
        {
            public uint PlatformId { get; set; }
            public byte ActionType { get; set; }
            public bool IntVersioningFlag { get; set; }
            public int IntVersion { get; set; }
        }

        public IpMacPlatform[] IpMacNotificationInfo { get; private set; }

        public byte[] DataBroadcastSelector { get; private set; }

        public ushort DataBroadcastId { get; private set; }

        public override byte[] Serialize()
        {
	        byte length = 2;
            if (DataBroadcastSelector != null)
				if (DataBroadcastSelector.Length > 253)
					throw new Exception("DataBroadcastSelector too long!");

	        if (DataBroadcastSelector != null)
		        length += (byte)(DataBroadcastSelector.Length);

	        byte[] bytes = BitConverter.GetBytes(DataBroadcastId);
	        if (BitConverter.IsLittleEndian)
		        Array.Reverse(bytes);

	        byte[] result = new byte[length];
	        result[0] = bytes[0];
	        result[1] = bytes[1];
	        if (DataBroadcastSelector != null)
		        Array.Copy(DataBroadcastSelector, 0, result, 2, DataBroadcastSelector.Length);

	        return result;
        }
    }
}
