using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using skyscraper5.Mpeg2;
using skyscraper5.Skyscraper.IO;
using skyscraper5.Dvb.Psi.Model;

namespace skyscraper5.Dvb.Psi
{
    class RstParser : IPsiProcessor
    {
        public IRstEventHandler EventHandler { get; }

        public RstParser(IRstEventHandler eventHandler)
        {
            EventHandler = eventHandler;
        }

        public void GatherPsi(PsiSection section, int sourcePid)
        {
            MemoryStream ms = new MemoryStream(section.GetDataCopy(), false);

            byte tableId = ms.ReadUInt8();
            if (tableId != 0x71)
                return;

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

            sectionLength /= 9;
            for (int i = 0; i < sectionLength; i++)
            {
                uint transportStreamId = ms.ReadUInt16BE();
                uint originalNetworkId = ms.ReadUInt16BE();
                uint serviceId = ms.ReadUInt16BE();
                uint eventId = ms.ReadUInt16BE();
                RunningStatus runningStatus = (RunningStatus)(int)(ms.ReadUInt8() & 0x07);
                EventHandler.NotifyRunningStatus(transportStreamId, originalNetworkId, serviceId, eventId, runningStatus);
            }
        }
    }
}
