using System;
using System.Collections.Specialized;
using System.IO;
using System.Threading.Tasks;
using MrWu.Debug;
using WebSocketSharp;
using WebSocketSharp.Server;
using ErrorEventArgs = WebSocketSharp.ErrorEventArgs;

namespace Server.Net
{
    public class GameWChannel : BaseWChannel
    {
        public long SessionId { get; set; }

        /// <summary>
        /// 链接成功事件
        /// </summary>
        public static event Action<GameWChannel> OnConnectedEvt;

        /// <summary>
        /// 收到包事件
        /// </summary>
        public static event Action<GameWChannel, byte[]> OnReceivedEvt;

        /// <summary>
        /// 断开连接事件
        /// </summary>
        public static event Action<GameWChannel> OnDisconnectedEvt;

        /// <summary>
        /// 发送错误事件
        /// </summary>
        public static event Action<GameWChannel, Exception> OnErrorEvt;


        //未收齐的字节，写入内存字节
        private MemoryStream _memoryStream = new MemoryStream();
        
        private bool waitReceiveHead = true;
        private int waitReceiveLength;

        public NameValueCollection WHeaders
        {
            get { return this.Headers; }
        }


        protected override void OnMessage(MessageEventArgs e)
        {
            base.OnMessage(e);

            // 收到包了!
            lock (_memoryStream)
            {
                _memoryStream.Write(e.RawData, 0, e.RawData.Length);
                _memoryStream.Seek(0, SeekOrigin.Begin);
                
                //Debug.Info($"OnMessage,{e.RawData.Length},{_memoryStream.Position},{_memoryStream.Length}");
                long byteLength = _memoryStream.Length - _memoryStream.Position;

                byte[] bodyData = new byte[byteLength];
                _memoryStream.Read(bodyData, 0, (int)byteLength);
                //Debug.Info($"收到包体:{_memoryStream.Position},{_memoryStream.Length},bodyLength:{waitReceiveLength}");
                waitReceiveHead = true;
                OnReceivedEvt?.Invoke(this, bodyData);

                _memoryStream.Seek(0, SeekOrigin.Begin);
                _memoryStream.SetLength(0);
            }
        }

        protected override void OnClose(CloseEventArgs e)
        {
            base.OnClose(e);
            OnDisconnectedEvt?.Invoke(this);
        }

        protected override void OnError(ErrorEventArgs e)
        {
            base.OnError(e);
            OnErrorEvt?.Invoke(this, e.Exception);
        }

        protected override void OnOpen()
        {
            base.OnOpen();
            OnConnectedEvt?.Invoke(this);
        }
    }
}