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(0xaa,"TIM")]
	internal class _0xaa_TableUpdateDescriptor : TsDescriptor
	{
		public _0xaa_TableUpdateDescriptor(byte[] buffer)
		{
			MemoryStream ms = new MemoryStream(buffer, false);
			InteractiveNetworkId = ms.ReadUInt16BE();

			long availableBytes = ms.GetAvailableBytes();
			if (availableBytes % 2 != 0)
			{
				Valid = false;
				return;
			}

			Updates = new TableUpdate[availableBytes / 2];
			for (int i = 0; i < Updates.Length; i++)
			{
				Updates[i] = new TableUpdate();
				Updates[i].TableId = ms.ReadUInt8();
				Updates[i].NewVersion = ms.ReadUInt8() & 0x1f;
			}
			Valid = true;
		}

		public ushort InteractiveNetworkId { get; }
		public TableUpdate[] Updates { get; }
		public struct TableUpdate
		{
			public byte TableId { get; internal set; }
			public int NewVersion { get; internal set; }
		}

		public override string ToString()
		{
			return String.Format("{0} table updates.", Updates.Length);
		}
	}
}
