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

namespace skyscraper5.Dvb.Descriptors
{
	[SkyscraperPlugin]
	[TsDescriptor(0x4e,"EIT")]
    class ExtendedEventDescriptor : TsDescriptor
    {
        private int _lastDescriptorNumber;

        public ExtendedEventDescriptor(byte[] buffer)
        {
            if (buffer.Length == 0)
                return;

            MemoryStream ms = new MemoryStream(buffer, false);

            byte readUInt8 = ms.ReadUInt8();
            DescriptorNumber = (readUInt8 & 0xf0) >> 4;
            LastDescriptorNumber = (readUInt8 & 0x0f);

            Iso639LanguageCode = Encoding.ASCII.GetString(ms.ReadBytes(3));

            byte lengthOfItems = ms.ReadUInt8();
            if (lengthOfItems > ms.GetAvailableBytes())
                return;
            byte[] itemsBuffer = ms.ReadBytes(lengthOfItems);
            if (!ParseItems(itemsBuffer))
            {
                Valid = false;
                return;
            }

            byte textLength = ms.ReadUInt8();
            Text = En300468AnnexATextDecoder.GetInstance().Decode(ms.ReadBytes(textLength));
            this.Valid = !string.IsNullOrEmpty(Text);
        }
        
        public string Text { get; private set; }

        private bool ParseItems(byte[] buffer)
        {
            MemoryStream ms = new MemoryStream(buffer, false);
            while (ms.Length - ms.Position > 0)
            {
                byte itemDescriptionLength = ms.ReadUInt8();
                if (itemDescriptionLength > ms.GetAvailableBytes())
                {
                    return false;
                }
                string itemDescription = En300468AnnexATextDecoder.GetInstance().Decode(ms.ReadBytes(itemDescriptionLength));
                byte itemLength = ms.ReadUInt8();
                string item = En300468AnnexATextDecoder.GetInstance().Decode(ms.ReadBytes(itemLength));

                if (Items == null)
                    Items = new List<KeyValuePair<string, string>>();
                Items.Add(new KeyValuePair<string, string>(itemDescription, item));
            }
            return true;
        }

        public string Iso639LanguageCode { get; private set; }

        public int LastDescriptorNumber
        {
            get
            {
                return _lastDescriptorNumber;
            }
            private set => _lastDescriptorNumber = value;
        }

        public int DescriptorNumber { get; private set; }

        public List<KeyValuePair<string,string>> Items { get; private set; }
    }
}
