using System.IO;

namespace skyscraper5.Mpeg2
{
    class PesDecoder : ITsPacketProcessor, IPayloadUnitDecoder
    {
        public IPesProcessor Sink { get; }

        public PesDecoder(IPesProcessor sink)
        {
            Sink = sink;
        }

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

        public void PushPacket(TsPacket packet)
        {
            if (packet.GetPayload() == null)
                return;
            
            pushed++;
            if (packet.PayloadUnitStart)
            {
                if (ms != null)
                {
                    //Payload start UND es gibt schon was, also muss die Unit zu Ende sein?
                    PesPacket pesPacket = new PesPacket(ms.ToArray());
                    Sink.ProcessPesPacket(pesPacket);
                }
                ms = new MemoryStream();
                ms.WriteByte(0);
                Span<byte> payload = packet.GetPayload();
                ms.Write(payload.ToArray(), 0, payload.Length);
                
            }
            else
            {
                if (ms == null)
                {
                    //Kein Payload Starter UND es gibt noch nichts. Können wir also wegschmeißen.
                    discarded++;
                }
                else
                {
                    Span<byte> payload = packet.GetPayload();
                    ms.Write(payload.ToArray(), 0, payload.Length);
                }
            }
        }

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