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

namespace skyscraper5.Mpeg2.Descriptors
{
	[SkyscraperPlugin]
	[TsDescriptor(0x25,"PMT")]
    [BannedTable("BAT")]
    class MetadataPointerDescriptor : TsDescriptor
    {
        public MetadataPointerDescriptor(byte[] buffer)
        {
            MemoryStream ms = new MemoryStream(buffer, false);
            MetadataApplicationFormat = ms.ReadUInt16BE();
            if (MetadataApplicationFormat == 0xffff)
            {
                MetadataApplicationFormatIdentifier = ms.ReadUInt32BE();
            }

            MetadataFormat = ms.ReadUInt8();
            if (MetadataFormat == 0xff)
            {
                MetadataFormatIdentifier = ms.ReadUInt32BE();
            }

            MetadataServiceId = ms.ReadUInt8();

            byte readUInt8 = ms.ReadUInt8();
            MetadataLocatorRecordFlag = (readUInt8 & 0x80) != 0;
            MpegCarriageFlag = (readUInt8 & 0x60) >> 5;

            if (MetadataLocatorRecordFlag)
            {
                byte metadataLocatorRecordLength = ms.ReadUInt8();
                MetadataLocatorRecord = ms.ReadBytes(metadataLocatorRecordLength);
            }

            if (MpegCarriageFlag <= 2)
            {
                ProgramNumber = ms.ReadUInt16BE();
            }

            if (MpegCarriageFlag == 1)
            {
                TransportStreamLocation = ms.ReadUInt16BE();
                TransportStreamId = ms.ReadUInt16BE();
            }

            PrivateData = ms.ReadBytes(ms.GetAvailableBytes());
        }

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

        public ushort? TransportStreamId { get; private set; }

        public ushort? TransportStreamLocation { get; private set; }

        public ushort? ProgramNumber { get; private set; }

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

        public int MpegCarriageFlag { get; private set; }

        public bool MetadataLocatorRecordFlag { get; private set; }

        public byte MetadataServiceId { get; private set; }

        public uint? MetadataFormatIdentifier { get; private set; }

        public ushort MetadataFormat { get; private set; }

        public uint? MetadataApplicationFormatIdentifier { get; private set; }

        public ushort MetadataApplicationFormat { get; private set; }
    }
}
