using System;
using System.Collections.Generic;
using System.ComponentModel;
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(0x50,"EIT","SDT")]
    [BannedTable("PMT","TSDT","BAT")]
    public class ComponentDescriptor : TsDescriptor
    {
        public ComponentDescriptor(byte[] buffer)
        {
            if (buffer == null)
            {
                this.Valid = false;
                return;
            }
            if (buffer.Length < 6)
            {
                this.Valid = false;
                return;
            }

            MemoryStream ms = new MemoryStream(buffer, false);
            byte readUInt8 = ms.ReadUInt8();

            StreamContentExt = readUInt8 & 0xf0 >> 4;
            StreamContent = readUInt8 & 0x0f;
            ComponentType = ms.ReadUInt8();
            ComponentTag = ms.ReadUInt8();
            Iso639LanguageCode = Encoding.ASCII.GetString(ms.ReadBytes(3));
            Text = En300468AnnexATextDecoder.GetInstance().Decode(ms.ReadBytes(ms.GetAvailableBytes()));
            this.Valid = true;
        }

        public string Text { get; private set; }

        public string Iso639LanguageCode { get; private set; }

        public byte ComponentTag { get; private set; }

        public byte ComponentType { get; private set; }

        public int StreamContent { get; private set; }

        public int StreamContentExt { get; private set; }

        protected bool Equals(ComponentDescriptor other)
        {
            return Iso639LanguageCode == other.Iso639LanguageCode && ComponentTag == other.ComponentTag && ComponentType == other.ComponentType && StreamContent == other.StreamContent && StreamContentExt == other.StreamContentExt;
        }

        public override bool Equals(object obj)
        {
            if (ReferenceEquals(null, obj)) 
                return false;
            if (ReferenceEquals(this, obj)) 
                return true;
            if (obj.GetType() != this.GetType()) 
                return false;
            return Equals((ComponentDescriptor)obj);
        }

        public override int GetHashCode()
        {
            return HashCode.Combine(Iso639LanguageCode, ComponentTag, ComponentType, StreamContent, StreamContentExt);
        }
    }
}
