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

namespace skyscraper5.Skyscraper.Scraper.StreamAutodetection
{
    class StreamTypeAutodetectionTest : IAutodetectionEventHandler
    {
        public StreamTypeAutodetectionTest()
        {
            TsDescriptorUnpacker descriptorUnpacker = TsDescriptorUnpacker.GetInstance();
            for (byte i = 0x80; i < 0xfe; i++)
            {
                descriptorUnpacker.SetUserDefined(i, true);
            }
        }

        public void PushPacket(byte[] buffer)
        {
            if (tsContext == null)
                tsContext = new TsContext();
            TsPacket packet = new TsPacket(buffer);
            int pid = (int)packet.PID;

            if (!tsContext.IsPidProcessorPresent(pid))
            {
                tsContext.RegisterPacketProcessor(pid, new StreamTypeAutodetection(pid,this));
                streamsLeft++;
            }

            tsContext.PushPacket(buffer);
        }

        public void IngestFromStream(Stream stream)
        {
            byte[] buffer = new byte[188];
            while (true)
            {
                if (stream.Read(buffer, 0, 188) != 188)
                    break;

                PushPacket(buffer);
            }
            stream.Close();
        }

        private TsContext tsContext;
        private int streamsLeft;
        public void AutodetectionSucessful(int pid, Contestant contestant, ProgramContext programContext)
        {
            streamsLeft--;
            Console.WriteLine("Detected {0} on PID {1:X4} ({2} left...)", contestant.Tag, pid, streamsLeft);
            tsContext.RegisterPacketProcessor(pid, new PacketDiscarder());
        }

        public void AutodetectionRuleOut(int pid, Contestant contestant, ProgramContext programContext)
        {
            throw new NotImplementedException();
        }
    }
}
