using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using skyscraper5.Mpeg2;
using skyscraper5.T2MI.Packets;
using skyscraper8.T2MI.Packets;

namespace skyscraper5.T2MI
{
    internal class TestApp : T2MIEventHandler
    {
        public TestApp(string s)
        {
            InputFile = new FileInfo(s);
        }

        public FileInfo InputFile { get; set; }

        public void Run()
        {
            FileStream fileStream = InputFile.OpenRead();
            int psize = 188;
            byte[] buffer = new byte[psize];
            TsContext tsContext = new TsContext();

            T2MIDecoder t2mi = new T2MIDecoder(0x1000, this);
            tsContext.RegisterPacketProcessor(0x1000, t2mi);

            while (psize == 188)
            {
                psize = fileStream.Read(buffer, 0, 188);
                tsContext.PushPacket(buffer);
            }
        }

        public void OnT2MiPacketLoss(int pid, byte expectedPacket, T2MIHeader header)
        {
        }

        private FileStream[] fileStreams;
        public void OnT2MiPacket(int pid, byte plp, byte[] basebandPacket)
        {
            if (fileStreams == null)
            {
                fileStreams = new FileStream[256];
            }

            if (fileStreams[plp] == null)
            {
                FileInfo fi = new FileInfo(String.Format("{0}.ts", plp));
                if (fi.Exists)
                    fi.Delete();
                fileStreams[plp] = fi.OpenWrite();
            }

            fileStreams[plp].Write(basebandPacket, 0, 188);
        }

        public void OnT2MiTimestamp(int pid, _0x20_DvbT2Timestamp t2Timestamp)
        {
            
        }

        public void OnT2MiIqData(int relatedPid, _0x31_IqData iqData)
        {
        }

        public void OnT2MiIqData(int relatedPid, _0x01_IqData iqData2)
        {
            
        }

        public void OnT2MiError(int relatedPid, int skyscraperErrorCode)
        {
            
        }

        public void OnT2MiL1Current(int relatedPid, _0x10_L1Current l1Current)
        {
            
        }

        public void OnT2MiArbitraryCellInsertion(int relatedPid, _0x02_ArbitraryCellInsertion arbitraryCellInsertion)
        {
            
        }

        public void OnT2MiBalancingCells(int relatedPid, byte frameIndex, uint numActiveBiasCellsPerP2)
        {
            
        }

        public void OnT2MiL1Future(int relatedPid, _0x11_L1Future l1Future)
        {
            
        }

        public void OnT2MiIndividualAddressing(int relatedPid, _0x21_IndividualAddressing individualAddressing)
        {
            
        }

        void T2MIEventHandler.OnFramingAndTimingInformation(int relatedPid, _0xF0_FramingTimingInformation fti)
        {
        }
    }
}
