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

namespace skyscraper5.src.InteractionChannel.Model.Descriptors
{
	[SkyscraperPlugin]
	[TsDescriptor(0xb6,"TIM")]
	internal class _0xb6_LlFecIdentifierDescriptor : TsDescriptor
	{
		public _0xb6_LlFecIdentifierDescriptor(byte[] buffer)
		{
			MemoryStream ms = new MemoryStream(buffer, false);
			byte loopCount = ms.ReadUInt8();

			int required = loopCount * 8;
			if (ms.GetAvailableBytes() > 8)
			{
				Valid = false;
				return;
			}

			LlFecIdentifiers = new LlFecIdentifier[loopCount];
			for (int i = 0; i < loopCount; i++)
			{
				ushort v = ms.ReadUInt16BE();
				LlFecIdentifiers[i] = new LlFecIdentifier();
				LlFecIdentifiers[i].LinkDirection = (v & 0x8000) != 0;
				LlFecIdentifiers[i].EncapsulationType = (v & 0x4000) != 0;
				if (!LlFecIdentifiers[i].EncapsulationType)
				{
					LlFecIdentifiers[i].ElementaryStreamId = (v & 0x1fff);
				}
				else
				{
					LlFecIdentifiers[i].GseFecId = (v & 0x3fff);
				}

				v = ms.ReadUInt16BE();
				LlFecIdentifiers[i].LlFec = (v & 0xc000) >> 14;
				LlFecIdentifiers[i].FrameSize = (v & 0x0e00) >> 9;
				LlFecIdentifiers[i].BufferTimeout = (v & 0x01e0) >> 6;
				LlFecIdentifiers[i].Dscp = (v & 0x001f);
				uint reserved = ms.ReadUInt32BE();
			}
		}

		private LlFecIdentifier[] LlFecIdentifiers { get; }

		class LlFecIdentifier
		{
			public bool LinkDirection { get; internal set; }
			public bool EncapsulationType { get; internal set; }
			public int ElementaryStreamId { get; internal set; }
			public int GseFecId { get; internal set; }
			public int LlFec { get; internal set; }
			public int FrameSize { get; internal set; }
			public int BufferTimeout { get; internal set; }
			public int Dscp { get; internal set; }
		}

		public override string ToString()
		{
			return String.Format("{0} LL-FEC Identifiers", LlFecIdentifiers.Length);
		}
	}
}
