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.Payload == 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);
                ms.Write(packet.Payload, 0, packet.Payload.Length);
                
            }
            else
            {
                if (ms == null)
                {
                    //Kein Payload Starter UND es gibt noch nichts. Können wir also wegschmeißen.
                    discarded++;
                }
                else
                {
                    ms.Write(packet.Payload, 0, packet.Payload.Length);
                }
            }
        }

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