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

namespace skyscraper8.Dvb.Descriptors.Extension
{
	[SkyscraperPlugin]
	[ExtensionDescriptor(0x00, "NIT","BAT","SDT","EIT","SIT")]
	public class _0x00_ImageIconDescriptor : skyscraper5.Dvb.ExtensionDescriptor
	{
		public _0x00_ImageIconDescriptor(byte[] buffer)
		{
			MemoryStream ms = new MemoryStream(buffer, false);
			byte byteA = ms.ReadUInt8();
			DescriptiorNumber = (byteA & 0x80) >> 4;
			LastDescriptorNumber = (byteA & 0x08);

			byte byteB = ms.ReadUInt8();
			int reservedFutureUse = (byteB & 0xf8);
			IconId = (byteB & 0x07);
			if (DescriptiorNumber == 0x00)
			{
				byte byteC = ms.ReadUInt8();
				IconTransportMode = (byteC & 0xc0) >> 6;
				bool positionFlag = (byteC & 0x20) != 0;
				if (positionFlag)
				{
					CoordinateSystem = (byteC & 0x1c);
					reservedFutureUse = (byteC & 0x03);
					byte byteD = ms.ReadUInt8();
					byte byteE = ms.ReadUInt8();
					byte byteF = ms.ReadUInt8();
					IconHorizontalOrigin = (byteD << 4);
					IconHorizontalOrigin += ((byteE & 0xf0) >> 4);
					IconVerticalOrigin = ((byteE & 0x0f) << 8);
					IconVerticalOrigin += byteF;
				}
				else
				{
					reservedFutureUse = (byteC & 0x1f);
				}

				byte iconTypeLength = ms.ReadUInt8();
				if (ms.GetAvailableBytes() < iconTypeLength)
				{
					Valid = false;
					return;
				}

				IconType = ms.ReadUTF8FixedLength(iconTypeLength);
				if (IconTransportMode == 0)
				{
					byte iconDataLength = ms.ReadUInt8();
					if (ms.GetAvailableBytes() < iconDataLength)
					{
						Valid = false;
						return;
					}
					IconData = ms.ReadBytes(iconDataLength);
				}
				else if (IconTransportMode == 1)
				{
					byte urlLength = ms.ReadUInt8();
					if (ms.GetAvailableBytes() < urlLength)
					{
						Valid = false;
						return;
					}
					Url = ms.ReadUTF8FixedLength(urlLength);
				}
			}
			else
			{
				byte iconDataLength = ms.ReadUInt8();
				if (ms.GetAvailableBytes() < iconDataLength)
				{
					Valid = false;
					return;
				}
				IconData = ms.ReadBytes(iconDataLength);
			}

			Valid = true;
		}

		public int IconId { get; set; }

		public string Url { get; set; }

		public byte[] IconData { get; set; }

		public string IconType { get; set; }

		public int? IconVerticalOrigin { get; set; }

		public int? IconHorizontalOrigin { get; set; }

		public int? CoordinateSystem { get; set; }

		public int? IconTransportMode { get; set; }

		public int LastDescriptorNumber { get; set; }

		public int DescriptiorNumber { get; set; }
	}
}
