using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using skyscraper5.Mhp.Descriptors.InteractionTransportSelectors;
using skyscraper5.Mpeg2;
using skyscraper5.Skyscraper.IO;
using skyscraper5.Skyscraper.Plugins;

namespace skyscraper5.Mhp.Descriptors
{
	[SkyscraperPlugin]
	[TsDescriptor(0x02,"AIT")]
    public class TransportProtocolDescriptor : TsDescriptor
    {
        public TransportProtocolDescriptor(byte[] buffer)
        {
            MemoryStream ms = new MemoryStream(buffer, false);
            ProtocolId = ms.ReadUInt16BE();
            TransportProtocolLabel = ms.ReadUInt8();

            if (ms.GetAvailableBytes() > 0)
            {
                switch (ProtocolId)
                {
                    case 0x0001:
                        Selector = new ObjectCarouselTransportSelector(ms);
                        break;
                    case 0x0003:
                        Selector = new InteractionTransportSelector(ms);
                        break;
                    default:
                        Console.WriteLine("TransportProtocolDescriptor: Unknown ProtocolId 0x{0:X4}", ProtocolId);
                        //TODO: Generischen Selektor bauen
                        Selector = null;
                        break;
                }
            }
            Valid = true;
        }

        public byte TransportProtocolLabel { get; private set; }

        public ushort ProtocolId { get; private set; }

        public TransportProtocolSelector Selector { get; private set; }

        protected bool Equals(TransportProtocolDescriptor other)
        {
            return TransportProtocolLabel == other.TransportProtocolLabel && ProtocolId == other.ProtocolId && Selector.Equals(other.Selector);
        }

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

        public override int GetHashCode()
        {
            unchecked
            {
                var hashCode = TransportProtocolLabel.GetHashCode();
                hashCode = (hashCode * 397) ^ ProtocolId.GetHashCode();
                hashCode = (hashCode * 397) ^ Selector.GetHashCode();
                return hashCode;
            }
        }
    }
}
