using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
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(0x38,"PMT")]
    [BannedTable("EIT")]
    class HevcVideoDescriptor : TsDescriptor
    {
        public HevcVideoDescriptor(byte[] buffer)
        {
            if (buffer.Length != 13 && buffer.Length != 15)
                return;

            MemoryStream ms = new MemoryStream(buffer, false);
            byte readUInt8 = ms.ReadUInt8();
            ProfileSpace = (readUInt8 & 0xc0) >> 6;
            TierFlag = (readUInt8 & 0x20) != 0;
            ProfileIdc = (readUInt8 & 0x1f);
            ProfileCompatibilityIndication = ms.ReadUInt32BE();

            readUInt8 = ms.ReadUInt8();
            ProgressiveSourceFlag = (readUInt8 & 0x80) != 0;
            InterlacedSourceFlag = (readUInt8 & 0x40) != 0;
            NonPackedConstraintFlag = (readUInt8 & 0x20) != 0;
            FrameOnlyConstraintFlag = (readUInt8 & 0x10) != 0;

            Copied44bits = readUInt8 & 0x0f;
            Copied44bits <<= 32;
            Copied44bits += ms.ReadUInt32BE();
            Copied44bits <<= 8;
            Copied44bits += ms.ReadUInt8();

            LevelIdc = ms.ReadUInt8();

            readUInt8 = ms.ReadUInt8();
            bool temporalLayerSubsetFlag = (readUInt8 & 0x80) != 0;
            HevcStillPresentFlag = (readUInt8 & 0x40) != 0;
            Hevc24hrPicturePresentFlag = (readUInt8 & 0x20) != 0;
            SubPicHrdParamsNotPresentFlag = (readUInt8 & 0x10) != 0;
            HdrWcgIdc = (readUInt8 & 0x02);

            if (temporalLayerSubsetFlag)
            {
                TemporalIdMin = (ms.ReadUInt8() & 0xe0) >> 5;
                TemporalIdMax = (ms.ReadUInt8() & 0xe0) >> 5;
            }

            base.Valid = true;
        }
        
        public int? TemporalIdMax { get; private set; }

        public int? TemporalIdMin { get; private set; }

        public int HdrWcgIdc { get; private set; }

        public bool SubPicHrdParamsNotPresentFlag { get; private set; }

        public bool Hevc24hrPicturePresentFlag { get; private set; }

        public bool HevcStillPresentFlag { get; private set; }

        public byte LevelIdc { get; private set; }

        public long Copied44bits { get; private set; }

        public bool FrameOnlyConstraintFlag { get; private set; }

        public bool NonPackedConstraintFlag { get; private set; }

        public bool InterlacedSourceFlag { get; private set; }

        public bool ProgressiveSourceFlag { get; private set; }

        public uint ProfileCompatibilityIndication { get; private set; }

        public int ProfileIdc { get; private set; }

        public bool TierFlag { get; private set; }

        public int ProfileSpace { get; private set; }
    }
}
