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

namespace skyscraper5.src.Skyscraper
{
	internal class DigitalDevicesBbFrameReader : ITsPacketProcessor
	{
		private IGsEventHandler mpeEventHandler;

		public DigitalDevicesBbFrameReader(IGsEventHandler mpeEventHandler)
		{
			this.mpeEventHandler = mpeEventHandler;
		}

		private MemoryStream outbuf;
		private bool annoncementDone;
		public void PushPacket(TsPacket packet)
		{
			byte[] packets = packet.RawPacket;
			int pid = (packets[1]);
			pid &= 0x01f;
			pid <<= 8;
			pid |= (packets[2]);
			if (pid != 0x010e)
				return;

			if ((packets[8] & 0xff) == 0xb8)
			{
				if (outbuf != null)
				{
					byte[] chi = outbuf.ToArray();
					byte[] ipPacket = IpPacketFinder.LookForIpPacket(outbuf.ToArray(), 32);
					if (ipPacket != null)
					{
						if (!annoncementDone)
						{
							mpeEventHandler.GsIpTrafficDetected();
							annoncementDone = true;
						}
						mpeEventHandler.OnIpDatagram(0x0118, ipPacket);
					}
				}
				outbuf = new MemoryStream();
				outbuf.Write(packets,8, packets[7]);
			}
			else
			{
				if (outbuf != null)
					outbuf.Write(packets, 9, packets[7] - 1);
			}
		}
	}
}
