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(0x79,"NIT")]
    [BannedTable("BAT","PMT")]
    public class S2SatelliteDeliverySystemDescriptor : TsDescriptor
    {
        public S2SatelliteDeliverySystemDescriptor(byte[] buffer)
        {
            if (buffer.Length == 0)
                return;

            MemoryStream ms = new MemoryStream(buffer, false);
            byte readUInt8 = ms.ReadUInt8();
            bool scramblingSequenceSelector = (readUInt8 & 0x80) != 0;
            bool multipleInputStreamFlag = (readUInt8 & 0x40) != 0;
            bool notTimesliceFlag = (readUInt8 & 0x10) != 0;
            TsGsMode = (TsGsModeCoding)(readUInt8 & 0x03);
            if (scramblingSequenceSelector)
            {
                ScramblingSequenceIndex = (readUInt8 & 0x03) << 16;
                ScramblingSequenceIndex += ms.ReadUInt16BE();
            }

            if (multipleInputStreamFlag)
            {
                InputStreamIdentifier = ms.ReadUInt8();
            }

            if (notTimesliceFlag)
            {
                if (ms.GetAvailableBytes() > 0)
                    TimesliceNumber = ms.ReadUInt8();
            }

            this.Valid = true;
        }
        
        public byte TimesliceNumber { get; private set; }

        public byte? InputStreamIdentifier { get; private set; }

        public int? ScramblingSequenceIndex { get; private set; }

        public TsGsModeCoding TsGsMode { get; private set; }

        public enum TsGsModeCoding : byte
        {
            GenericPacketized = 0,
            Gse = 1,
            TransportStream = 2
        }
    }
}
