using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using log4net;
using skyscraper5.Dvb;
using skyscraper5.Dvb.DataBroadcasting;
using skyscraper5.Mpeg2;
using skyscraper5.Skyscraper.IO;

namespace skyscraper5.Skyscraper
{
    internal class OldStreamReaderDetector : ITsPacketProcessor
    {
	    private static readonly ILog logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name);

		public OldStreamReaderDetector()
        {
        }

        private MemoryStream outbuf;
        private int assembled;
        private bool annoncementDone;

        public void PushPacket(TsPacket packet)
        {
	        if (annoncementDone)
		        return;

	        byte[] packets = packet.GetRawPacket();
	        int pid = (packets[1]);
	        pid &= 0x01f;
	        pid <<= 8;
	        pid |= (packets[2]);
	        if (pid != 0x0118)
		        return;

            if ((packets[8] & 0xff) == 0xd0)
            {
                if (outbuf != null)
                {
                    byte[] chi = outbuf.ToArray();
                    byte[] ipPacket = IpPacketFinder.LookForIpPacket(outbuf.ToArray());
                    if (ipPacket != null)
                    {
                        if (!annoncementDone)
                        {
                            logger.WarnFormat("It seems like you're using a StreamReader.dll version which interferes with the STiD135's BBFrame encapsulation. Try updating to 1.2.5.208, this is known to work.");
                            annoncementDone = true;
                        }
                    }
                }
                outbuf = new MemoryStream();
                outbuf.Write(packets, 8, packets[7]);
            }
            else
            {
                int length = packets[7] - 1;
                if (length + 9 <= packets.Length)
                {
					if (outbuf != null)
						outbuf.Write(packets, 9, length);
				}
                else
                {
                    //broken packet, discard.
                    outbuf = null;
                }
            }
        }
    }
}
