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.Dvb;
using System.IO;
using skyscraper5.Skyscraper.IO;
using skyscraper5.Skyscraper.Text;

namespace skyscraper5.src.Dvb.Descriptors.Extension
{
	[SkyscraperPlugin]
	[ExtensionDescriptor(0x20, "PMT")]
	class _0x20_TtmlSubtitlingDescriptor : ExtensionDescriptor
	{
		public _0x20_TtmlSubtitlingDescriptor(byte[] buffer)
		{
			MemoryStream ms = new MemoryStream(buffer, false);
			Iso639LanguageCode = ms.ReadUTF8FixedLength(3);

			byte byteA = ms.ReadUInt8();
			SubtitlePurpose = (SubtitlePurposeEnum)((byteA >> 2) & 0x3f);
			TtsSustainability = (TtsSustainabilityEnum)(byteA & 0x03);

			byte byteB = ms.ReadUInt8();
			bool essentialFontUsageFlag = (byteB & 0x80) != 0;
			bool qualifierPresentFlag = (byteB & 0x40) != 0;
			int ttmlProfileCount = (byteB & 0x0f);
			DvbTtmlProbile = ms.ReadBytes(ttmlProfileCount);
			if (qualifierPresentFlag)
			{
				Qualifier = (uint?)ms.ReadUInt32BE();
			}
			if (essentialFontUsageFlag)
			{
				int fontCount = ms.ReadUInt8();
				FontId = new int[fontCount];
				for (int i = 0; i < FontId.Length; i++)
				{
					FontId[i] = ms.ReadUInt8() & 0x7f;
				}
			}

			byte textLength = ms.ReadUInt8();
			TextChar = En300468AnnexATextDecoder.GetInstance().Decode(ms.ReadBytes(textLength));
			Valid = true;
		}

		public string Iso639LanguageCode { get; }
		public SubtitlePurposeEnum SubtitlePurpose { get; }
		public TtsSustainabilityEnum TtsSustainability { get; }
		public byte[] DvbTtmlProbile { get; }
		public uint? Qualifier { get; }
		public int[] FontId { get; }
		public string TextChar { get; }

		public enum SubtitlePurposeEnum : byte
		{
			SameLanguageDialogue = 0x00,
			OtherLanguageDialogue = 0x01,
			AllDialogue = 0x02,
			HardOfHearing = 0x10,
			OtherLanguageDialogueWithHardOfHearing = 0x11,
			AllDialogueWithHardOfHearing = 0x12,
			AudioDescription = 0x30,
			ContentRelatedCommentary = 0x31
		}

		public enum TtsSustainabilityEnum : byte
		{
			Unknown = 0x00,
			Suitable = 0x01,
			Unsuitable = 0x02
		}
	}
}
