
using System;
using System.Collections;
using System.Collections.Generic;
using Google.Protobuf;
using NativeWebSocket;
using Unity.Muninn.Message;
using UnityEngine;

namespace Unity.Muninn.Transport
{
    public class MuninnWebsocketClient : MuninnTransportClient
    {

        private WebSocket websocket;

        public event Action<MuninnEvent> OnDispatchEvent;
        
        // 客户端在传输层，connected, 默认需要调用
        public event Action OnConnectedCallback;
        
        // 客户端在传输层，disconnected消息
        public event Action OnDisconnectedCallback;
        
        private MuninnConnectionStatus _status = MuninnConnectionStatus.Init;
        
        private Unity.Muninn.Message.IOBuffer _ioBuffer = new Unity.Muninn.Message.IOBuffer();
        
        // public MuninnWebsocketClient(
        //     Action OnConnectedCallback,
        //     Action<MuninnEvent> OnDispatchEvent,
        //     Action OnDisconnectedCallback
        // ) : base(OnConnectedCallback, OnDispatchEvent, OnDisconnectedCallback)
        // {
        // }
        
        public MuninnWebsocketClient(
            Action OnConnectedCallback,
            Action<MuninnEvent> OnDispatchEvent,
            Action OnDisconnectedCallback
        )
        {
            this.OnConnectedCallback = OnConnectedCallback;
            this.OnDispatchEvent = OnDispatchEvent;
            this.OnDisconnectedCallback = OnDisconnectedCallback;
        }
    
        async void Start(string serverIp, int serverPort)
        {
            // websocket = new WebSocket("ws://echo.websocket.org");

            Dictionary<string, string> headers = new Dictionary<string, string>();
            string uri = string.Format("ws://{0}:{1}/room/ws", serverIp, serverPort);
            if (MuninnSettings.TransportType == MuninnTransportType.WebSocketSecure)
            {
                // uri = "wss://wsp.unity.cn:443/room/ws";
                uri = $"{MuninnSettings.WebsocketProxy}/room/ws?ip={serverIp}&port={serverPort}" ;
                // headers["x-instance-ip"] = serverIp;
                // headers["x-instance-port"] = $"{serverPort}";
            }

            Debug.Log("connect to uri: " + uri);
            
            websocket = new WebSocket(uri, headers);
            _ioBuffer = new Unity.Muninn.Message.IOBuffer();

            websocket.OnOpen += () =>
            {
                Debug.Log("Connection open!");
                _status = MuninnConnectionStatus.Connected;
                OnConnectedCallback?.Invoke();
            };

            websocket.OnError += (e) =>
            {
                // 这边需要加相关的操作
                 Debug.Log("Websocket Error! " + e);
                this.Disconnect();
            };

            websocket.OnClose += (e) =>
            {
                Debug.Log("Connection closed!");
                _status = MuninnConnectionStatus.Closed;
                OnDisconnectedCallback?.Invoke();
                this.CleanUp();
            };

            websocket.OnMessage += (bytes) =>
            {
                if (_status != MuninnConnectionStatus.Connected) return;
                List<MuninnEvent> evts = _ioBuffer.read(bytes, bytes.Length);
                foreach (MuninnEvent e in evts)
                {
                    OnDispatchEvent?.Invoke(e);
                }
            };
            await websocket.Connect();
        }

        public override void Init(string socketIP, ushort socketPort)
        {
            Start(socketIP, socketPort);
        }

        public override void Update()
        {
#if !UNITY_WEBGL || UNITY_EDITOR
            // if (websocket != null)
            if (websocket != null)
            {
                websocket.DispatchMessageQueue();
            }
#endif
        }

        public override void SendEvent(MuninnEvent eEvent)
        {
            if (IsConnected())
            {
                byte[] data = eEvent.ToByteArray();
                byte[] res = MuninnBaseHeader.SendMessageWithoutLimit(data);
                SendWebSocketMessage(res);
            }
        }

        public override bool IsConnected()
        {
            return _status == MuninnConnectionStatus.Connected;
        }

        async void SendWebSocketMessage(byte[] data)
        {
            if (websocket != null && websocket.State == WebSocketState.Open)
            {
                // Sending bytes
                await websocket.Send(data);
            }
        }

        public override void Disconnect()
        {
            if (websocket != null && websocket.State == WebSocketState.Open)
            {
                websocket.Close();
                Debug.Log("Disconnect in websocket");
            }
        }

        public override void OnDestroy()
        {
            CleanUp();
        }

        private void CleanUp()
        {
            _status = MuninnConnectionStatus.Closed;
            this.websocket = null;
                
            if (_ioBuffer != null)
            {
                _ioBuffer.Dispose();
                _ioBuffer = null;
            }
        }

        // 永远都行
        public override bool Available() => true;

        public override void AddDispatchEvent(Action<MuninnEvent> callback)
        {
            this.OnDispatchEvent += callback;
        }

    }
    
    // *) 然后使用
    public class MuninnWebsocketTransportFactory : MuninnTransportFactory
    {
        
        // // 在静态构造函数里, 进行注册
        // static MuninnWebsocketTransportFactory()
        // {
        //     MuninnTransportFactoryRegistry.Register(MuninnTransportType.Websocket, new MuninnWebsocketTransportFactory());
        // }

        // 工厂方法
        public override MuninnTransportClient Create(
            Action OnConnectedCallback,
            Action<MuninnEvent> OnDispatchEvent,
            Action OnDisconnectedCallback
        )
        {
            return new MuninnWebsocketClient(OnConnectedCallback, OnDispatchEvent, OnDisconnectedCallback);
        }

    }
    
    
}