using System;
using System.Collections.Generic;

namespace skyscraper5.Scorcher
{
	internal class DataPipingGenerator : IPacketGenerator
	{
		public DataPipingGenerator(uint pid)
		{
			this.backlog = new Queue<byte[]>();
			this.pid = pid;
			this.pusi = true;
		}

		private bool pusi;
		private Queue<byte[]> backlog;
		private long backlogLength;
		public void Append(byte[] buffer)
		{
			backlog.Enqueue(buffer);
			backlogLength += buffer.Length;
		}

		private byte[] currentItem;
		private int currentItemLength;
		private int currentItemOffset;
		private readonly uint pid;

		private int CurrentItemRemaining
		{
			get
			{
				return currentItem != null ? currentItemLength - currentItemOffset : 0;
			}
		}

		public bool PacketAvailable()
		{
			if ((CurrentItemRemaining + backlogLength) > 184)
				return true;

			return false;
		}

		private int continuity;
		public byte[] GeneratePacket()
		{
			byte[] buildHeader = TsPacketHeaderBuilder.BuildHeader(pusi, pid, continuity++);
			int bytesLeft = 188;
			byte[] buffer = new byte[188];
			Array.Copy(buildHeader, 0, buffer, 0, buildHeader.Length);
			bytesLeft -= 4;
			while (bytesLeft > 0)
			{
				if (CurrentItemRemaining == 0)
				{
					currentItem = backlog.Dequeue();
					currentItemLength = currentItem.Length;
					currentItemOffset = 0;
					backlogLength -= currentItem.Length;
				}

				int copyLength = Math.Min(CurrentItemRemaining, bytesLeft);
				Array.Copy(currentItem, 0, buffer, 188 - bytesLeft, copyLength);
				currentItemOffset += copyLength;
				bytesLeft -= copyLength;
			}
			return buffer;
		}
	}
}
