using System;
using System.IO;
using skyscraper5.Mpeg2;

namespace skyscraper5.Skyscraper.Scraper.Utils
{
    class PayloadUnitDumper : IPayloadUnitDecoder, ITsPacketProcessor
    {
        private ulong serial;

        private MemoryStream targetPs;
        private long pushed;
        private long discarded;
        public object Tag { get; set; }

        public void PushPacket(TsPacket packet)
        {
            pushed++;
            if (packet.PayloadUnitStart)
            {
                if (targetPs != null)
                {
                    //Unit zu Ende...
                    DirectoryInfo outDir = new DirectoryInfo("dumped_pus");
                    if (!outDir.Exists)
                        outDir.Create();
                    FileInfo fi = new FileInfo(Path.Combine(outDir.FullName,String.Format("PID{0:X4}_{1:D8}.pu", packet.PID, ++serial)));
                    if (!fi.Exists)
                    {
                        FileStream fileStream = fi.OpenWrite();
                        targetPs.Position = 0;
                        targetPs.CopyTo(fileStream);
                        targetPs.Flush();
                        fileStream.Close();
                        targetPs.Close();
                        if (Tag != null)
                        {
                            Console.WriteLine(Tag.ToString());
                        }
                    }
                }

                Span<byte> payload = packet.GetPayload();
                targetPs = new MemoryStream();
                targetPs.Write(payload);

            }
            else
            {
                if (targetPs == null)
                {
                    //Kein Payload Starter UND es gibt noch nichts. Können wir also wegschmeißen.
                    discarded++;
                }
                else
                {
                    Span<byte> payload = packet.GetPayload();
                    targetPs.Write(payload);
                }
            }
        }

        public void PacketLoss()
        {
            targetPs = null;
        }
    }
}
