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

namespace skyscraper5.Eacem.Descriptors
{
    //The official EICTA/EACEM specification is not available, so this is guesswork.
    //Guesses taken from https://confindustriaradiotv.it/wp-content/uploads/2021/03/HD-Z-BOOK-Final-1.0.pdf
    [SkyscraperPlugin]
    [UserDefinedDescriptor(0x00000028, 0x83,"NIT","BAT")]
    [BannedTable("SDT")]    // <-- According to a document from ziggo.
    [DescriptorPluginNitHandler(typeof(NitHook))]
    [DescriptorPluginBatHandler(typeof(BatHook))]
    class EacemLogicalChannelDescriptor : TsDescriptor
    {
        public EacemLogicalChannelDescriptor(byte[] buffer)
        {
            LogicalChannels = new LogicalChannelNumberEntry[buffer.Length / 4];
            MemoryStream ms = new MemoryStream(buffer, false);
            for (int i = 0; i < LogicalChannels.Length; i++)
            {
                LogicalChannelNumberEntry lcn = new LogicalChannelNumberEntry();
                LogicalChannels[i] = lcn;

                lcn.ServiceId = ms.ReadUInt16BE();
                ushort readUInt16Be = ms.ReadUInt16BE();
                lcn.VisibleServiceFlag = (readUInt16Be & 0x8000) != 0;
                lcn.LogicalChannelNumber = (readUInt16Be & 0x03ff);
            }
        }

        public LogicalChannelNumberEntry[] LogicalChannels { get; private set; }

        public class LogicalChannelNumberEntry : BaseLcn
        {
            public bool VisibleServiceFlag { get; set; }
        }
    }
}
