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;
using skyscraper8.Skyscraper;

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

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

		private long packetsRecovered;
		private long packetsLost;
		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();
					if (deencapsulator == null)
					{
						deencapsulator = new BbframeDeencapsulator();
						deencapsulator.MpeEventHandler = mpeEventHandler;
						deencapsulator.PID = pid;
					}

					deencapsulator.PushPacket(chi);
				}
				outbuf = new MemoryStream();
				outbuf.Write(packets,9, packets[7] - 1);
			}
			else
			{
				if (outbuf != null)
					outbuf.Write(packets, 9, packets[7] - 1);
			}
		}
	}
}
