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 skyscraper5.Dvb.DataBroadcasting;
using skyscraper8.GS;
using skyscraper8.Skyscraper.Scraper;

namespace skyscraper8.GSE
{
	internal class Stid135BbFrameReader : ITsPacketProcessor
	{
		private IBbframeDeencapsulator deencapsulator;

		public Stid135BbFrameReader(GsContextDto context, IBbframeDeencapsulator deencapsulator = null)
		{
			if (deencapsulator == null)
				deencapsulator = new BbframeDeencapsulator3(context);
			
			this.deencapsulator = deencapsulator;
		}

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

			if (outbuf == null)
				outbuf = new MemoryStream();
			
			if ((packets[8] & 0xff) == 0xb8)
			{
				if (outbuf.Length > 0)
				{
					byte[] completeBbframe = outbuf.ToArray();
					deencapsulator.PushPacket(completeBbframe);
					outbuf = new MemoryStream();
				}
				
				//Start indicaator
				outbuf.Write(packets, 8, packets[7]);
			}
			else
			{
				outbuf.Write(packets, 9, packets[7] - 1);
			}
		}
	}
}
