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

namespace skyscraper8.DvbSis
{
    internal class DsAciHandler : IPsiProcessor
    {
        private readonly SisHandler sisOutput;

        public DsAciHandler(SisHandler sisOutput)
        {
            this.sisOutput = sisOutput;
        }

        public void GatherPsi(PsiSection section, int sourcePid)
        {
            byte[] bytes = section.GetData();
            MemoryStream ms = new MemoryStream(bytes, false);

            byte tableId = ms.ReadUInt8();

            byte byteA = ms.ReadUInt8();
            bool sectionSyntaxIndicator = (byteA & 0x80) != 0;
            bool reservedFutureUse = (byteA & 0x40) != 0;
            int reservedA = (byteA & 0x30) >> 4;

            int sectionLength = (byteA & 0x0f);
            sectionLength <<= 8;
            sectionLength += ms.ReadUInt8();

            ushort currentDsaGroupId = ms.ReadUInt16BE();

            byte byteB = ms.ReadUInt8();
            int reservedB = (byteB & 0xc0) >> 6;
            int versionNumber = (byteB & 0x3e) >> 1;
            bool currentNextIndicator = (byteB & 0x01) != 0;

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

            byte[] dsaciFileData = ms.ReadBytes(ms.GetAvailableBytes() - 4);

            uint crc32 = ms.ReadUInt32BE();

            PushSection(currentDsaGroupId, versionNumber, sectionNumber, lastSectionNumber, dsaciFileData);
        }

        private void PushSection(ushort currentDsaGroupId, int versionNumber, byte sectionNumber, byte lastSectionNumber, byte[] dsaciFileData)
        {
            if (sectionNumber == 0 && lastSectionNumber == 0)
            {
                MemoryStream ms = new MemoryStream(dsaciFileData, false);
                sisOutput.OnSisDsaci(currentDsaGroupId, versionNumber, sectionNumber, lastSectionNumber, ms);
                return;
            }
            else
            {
                throw new NotImplementedException("A DSACI Configuration spanning more than one section was detected. This is not supported yet. It would be great if you could share a sample of this stream, so I can fix it. \n - Cheers, Fey");
            }
        }
    }
}
