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

namespace skyscraper5.Dvb.DataBroadcasting
{
    class MpeFecSectionParser : IPsiProcessor
    {
        public void GatherPsi(PsiSection section, int sourcePid)
        {
            byte[] dataCopy = section.GetDataCopy();
            MemoryStream ms = new MemoryStream(dataCopy, false);
            byte table_id = ms.ReadUInt8();
            if (table_id != 0x78)
                return;

            ushort readUInt16Be = ms.ReadUInt16BE();
            bool sectionSyntaxIndicator = (readUInt16Be & 0x8000) != 0;
            bool privateIndicator = (readUInt16Be & 0x4000) != 0;
            int sectionLength = (readUInt16Be & 0x0fff);

            byte paddinggColumns = ms.ReadUInt8();

            byte readUInt8 = ms.ReadUInt8();    //reserved for future use
            readUInt8 = ms.ReadUInt8();
            bool currentNextIndicator = (readUInt8 & 0x01) != 0;

            byte sectionNumber = ms.ReadUInt8();
            byte lastSectionNumber = ms.ReadUInt8();

            RealTimeParameters realTimeParameters = new RealTimeParameters(ms.ReadUInt32BE());

            long rsDataLength = ms.GetAvailableBytes() - 4;
            byte[] rsData = ms.ReadBytes(rsDataLength);
            
            uint crc32 = ms.ReadUInt32BE();
        }

        class RealTimeParameters
        {
            public RealTimeParameters(uint value)
            {
                DeltaT = (value & 0xfff00000) >> 20;
                TableBoundary = (value & 0x00080000) != 0;
                FrameBoundary = (value & 0x00040000) != 0;
                Address = (value & 0x0003ffff);
            }

            public uint Address { get; private set; }

            public bool FrameBoundary { get; private set; }

            public bool TableBoundary { get; private set; }

            public uint DeltaT { get; private set; }
        }
    }
}
