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

namespace skyscraper5.Mhp.Descriptors.InteractionTransportSelectors
{
    public class ObjectCarouselTransportSelector : TransportProtocolSelector
    {
        internal ObjectCarouselTransportSelector(MemoryStream ms) : base(1)
        {
            byte readUInt8 = ms.ReadUInt8();
            RemoteConnection = (readUInt8 & 0x80) != 0;
            if (RemoteConnection)
            {
                OriginalNetworkId = ms.ReadUInt16BE();
                TransportStreamId = ms.ReadUInt16BE();
                ServiceId = ms.ReadUInt16BE();
            }

            ComponentTag = ms.ReadUInt8();
        }

        public byte ComponentTag { get; set; }

        public ushort? ServiceId { get; set; }

        public ushort? TransportStreamId { get; set; }

        public ushort? OriginalNetworkId { get; set; }

        public bool RemoteConnection { get; private set; }

        protected bool Equals(ObjectCarouselTransportSelector other)
        {
            return ComponentTag == other.ComponentTag && ServiceId == other.ServiceId && TransportStreamId == other.TransportStreamId && OriginalNetworkId == other.OriginalNetworkId && RemoteConnection == other.RemoteConnection;
        }

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

        public override int GetHashCode()
        {
            unchecked
            {
                var hashCode = ComponentTag.GetHashCode();
                hashCode = (hashCode * 397) ^ ServiceId.GetHashCode();
                hashCode = (hashCode * 397) ^ TransportStreamId.GetHashCode();
                hashCode = (hashCode * 397) ^ OriginalNetworkId.GetHashCode();
                hashCode = (hashCode * 397) ^ RemoteConnection.GetHashCode();
                return hashCode;
            }
        }

        public override string ToString()
        {
            if (ServiceId.HasValue)
                return String.Format("DSM-CC Network {2}, TS #{3}, Service {1}, Component Tag {0}", ComponentTag, ServiceId.Value, OriginalNetworkId.Value, TransportStreamId.Value);
            return String.Format("DSM-CC Component Tag {0}", ComponentTag, ServiceId);
        }
    }
}
