using System;
using System.Collections.Generic;
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(0x64,"SDT","EIT")]
    class DataBroadcastDescriptor : TsDescriptor
    {
        public DataBroadcastDescriptor(byte[] buffer)
        {
            MemoryStream ms = new MemoryStream(buffer, false);
            DataBroadcastId = ms.ReadUInt16BE();
            ComponentTag = ms.ReadUInt8();
            byte selectorLength = ms.ReadUInt8();
            Selector = ms.ReadBytes(selectorLength);
            Iso639LanguageCode = Encoding.ASCII.GetString(ms.ReadBytes(3));
            byte textLength = ms.ReadUInt8();
            Text = En300468AnnexATextDecoder.GetInstance().Decode(ms.ReadBytes(textLength));
        }

        public DataBroadcastDescriptor(ushort dataBroadcastId, byte componentTag, byte[] selector, string languageCode, string text)
        {
            DataBroadcastId = dataBroadcastId;
            ComponentTag = componentTag;
            Selector = selector;
            Iso639LanguageCode = languageCode;
            Text = text;
        }


        public string Text { get; private set; }

        public string Iso639LanguageCode { get; private set; }

        public byte[] Selector { get; private set; }

        public byte ComponentTag { get; private set; }

        public ushort DataBroadcastId { get; private set; }

        public override byte[] Serialize()
        {
	        MemoryStream ms = new MemoryStream();
	        ms.WriteUInt16BE(DataBroadcastId);
	        ms.WriteUInt8(ComponentTag);

	        byte selectorLength = 0;
	        if (Selector != null)
	        {
		        if (Selector.Length > 255)
			        throw new Exception("Selector too long");
		        selectorLength = (byte)Selector.Length;
	        }

	        ms.WriteUInt8(selectorLength);
            if (Selector != null)
				ms.Write(Selector, 0, Selector.Length);
	        ms.Write(Encoding.ASCII.GetBytes(Iso639LanguageCode), 0, 3);

	        byte[] textBuffer = En300468AnnexATextDecoder.GetInstance().Encode(Text);
	        if (textBuffer.Length > 255)
		        throw new Exception("Text too long!");

	        ms.WriteUInt8((byte)textBuffer.Length);
	        ms.Write(textBuffer, 0, textBuffer.Length);
            return ms.ToArray();
        }
    }
}
