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

namespace skyscraper5.Mpeg2.Descriptors
{
	[SkyscraperPlugin]
	[TsDescriptor(0x09,"CAT","PMT")]
    [BannedTable("NIT")]
    public class CaDescriptor : TsDescriptor
    {
        public CaDescriptor(byte[] buffer)
        {
            MemoryStream ms = new MemoryStream(buffer, false);
            CaSystemId = ms.ReadUInt16BE();
            CaPid = ms.ReadUInt16BE() & 0x1fff;
            PrivateData = ms.ReadBytes(ms.GetAvailableBytes());
        }

        public CaDescriptor(ushort caSystemId, int caPid, byte[] privateData)
        {
            CaSystemId = caSystemId;
            CaPid = caPid;
            PrivateData = privateData;
        }

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

        public int CaPid { get; private set; }

        public ushort CaSystemId { get; private set; }

        protected bool Equals(CaDescriptor other)
        {
            return CaPid == other.CaPid && CaSystemId == other.CaSystemId;
        }

        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((CaDescriptor)obj);
        }

        public override int GetHashCode()
        {
            return HashCode.Combine(CaPid, CaSystemId);
        }

        public override byte[] Serialize()
        {
	        MemoryStream ms = new MemoryStream();
	        ms.WriteUInt16BE(CaSystemId);
	        ms.WriteUInt16BE((ushort)(CaPid & 0x1fff));
	        if (PrivateData != null)
		        ms.Write(PrivateData, 0, PrivateData.Length);
            return ms.ToArray();
        }
    }
}
