using System;
using System.Collections.Generic;
using System.Linq;
using Google.Protobuf;
using Unity.Muninn.Message;
using Unity.Muninn.Model;
using Unity.Muninn.Transport;
using UnityEngine;
using CodedEvent = Unity.Muninn.Model.CodedEvent;
using MuninnEvent = Unity.Muninn.Message.MuninnEvent;
using MuninnPlayer = Unity.Muninn.Model.MuninnPlayer;
using RaiseEventTarget = Unity.Muninn.Model.RaiseEventTarget;
using SliceOperation = Unity.Muninn.Model.SliceOperation;
using StickyEventScope = Unity.Muninn.Model.StickyEventScope;
using RaiseEventOptions = Unity.Muninn.Model.RaiseEventOptions;

namespace Unity.Muninn
{
    /// <summary>
    /// 定义了UOS Sync客户端异步回调接口。开发者根据自己的游戏逻辑去实现这些接口。
    /// </summary>
    public partial class MuninnBehaviour : MonoBehaviour
    {
        private MuninnNetworkEndpoint _muninnNetworkEndpoint;

        private MuninnTransportClient _muninnClient;

        private MuninnHeartbeatTimer _muninnHeartbeatTimer = new MuninnHeartbeatTimer();

        // private Dictionary<string, object> _traceMaps = new Dictionary<string, object>();

        private long _startFetchTime;

        public long? ServerTimeDelta { get; private set; }

        public bool IsConnected => _muninnClient != null && _muninnClient.IsConnected();

        public void SetupMuninnCallbacks()
        {
            MuninnNetwork.ActiveMonoBehaviour = this;
            MuninnNetwork.Timeout = 15;
            Debug.Log("Setup callback successfully for Muninn Sdk!");
        }

        public virtual void Awake()
        {
            SetupMuninnCallbacks();
        }

        public virtual void Update()
        {
            MuninnUpdate();
        }

        public virtual void OnDestroy()
        {
            _muninnClient?.OnDestroy();
            MuninnNetwork.ActiveMonoBehaviour = null;
        }

        public virtual void OnApplicationQuit()
        {
            this.Disconnect();
            // 不写
            // this.OnDisconnectedTransport();
        }

        public void LeaveRoom()
        {
            if (_muninnClient == null || !_muninnClient.IsConnected())
            {
                Debug.Log("MuninnClient had closed");
                return;
            }

            MuninnEvent e = new MuninnEvent()
            {
                LeaveRoomRequest = new LeaveRoomRequest()
            };
            SendMuninnEvent(e);
        }

        public void Disconnect()
        {
            if (_muninnRoomView == null)
            {
                _muninnClient?.Disconnect();
            }
            else
            {
                LeaveRoom();
            }
        }


        public void SubscribeGroups(List<uint> groups)
        {
            if (groups == null)
            {
                return;
            }

            MuninnEvent e = new MuninnEvent()
            {
                SubscribeGroupsRequest = new SubscribeGroupsRequest()
                {
                    GroupIds = { groups }
                }
            };
            SendMuninnEvent(e);
        }

        public void UnsubscribeGroups(List<uint> groups)
        {
            if (groups == null)
            {
                return;
            }

            MuninnEvent e = new MuninnEvent()
            {
                UnsubscribeGroupsRequest = new UnsubscribeGroupsRequest()
                {
                    GroupIds = { groups }
                }
            };
            SendMuninnEvent(e);
        }

        /// <summary>
        /// 添加CachedEvent
        /// </summary>
        /// <param name="tag"></param>
        /// <param name="data"></param>
        [Obsolete("该函数已废弃")]
        public void AddCachedEvent(string tag, byte[] data)
        {
            MuninnEvent e = new MuninnEvent()
            {
                AddCachedEventRequest = new AddCachedEventRequest()
                {
                    Tag = tag,
                    Data = ByteString.CopyFrom(data),
                }
            };
            SendMuninnEvent(e);
        }

        /// <summary>
        /// 添加CachedEvent
        /// </summary>
        /// <param name="tag"></param>
        /// <param name="data"></param>
        /// <param name="callback"></param>
        public void AddCachedEvent(string tag, byte[] data, Action<MuninnAddCachedEventResponse> callback)
        {
            string traceId = Guid.NewGuid().ToString();
            MuninnEvent e = new MuninnEvent()
            {
                AddCachedEventRequest = new AddCachedEventRequest()
                {
                    TraceId = traceId,
                    Tag = tag,
                    Data = ByteString.CopyFrom(data),
                }
            };
            SendMuninnEvent(e);

            RegisterOperationCallback(MuninnOpActionType.AddCachedEvent, traceId, callback);
        }

        /// <summary>
        /// 移除CachedEvent
        /// </summary>
        /// <param name="tag"></param>
        [Obsolete("该函数已废弃")]
        public void RemoveCachedEvent(string tag)
        {
            MuninnEvent e = new MuninnEvent()
            {
                RemoveCachedEventRequest = new RemoveCachedEventRequest()
                {
                    Tag = tag,
                }
            };
            SendMuninnEvent(e);
        }

        /// <summary>
        /// 移除CachedEvent
        /// </summary>
        /// <param name="tag"></param>
        /// <param name="callback"></param>
        public void RemoveCachedEvent(string tag, Action<MuninnRemoveCachedEventResponse> callback)
        {
            string traceId = Guid.NewGuid().ToString();
            MuninnEvent e = new MuninnEvent()
            {
                RemoveCachedEventRequest = new RemoveCachedEventRequest()
                {
                    TraceId = traceId,
                    Tag = tag,
                }
            };
            SendMuninnEvent(e);

            RegisterOperationCallback(MuninnOpActionType.RemoveCachedEvent, traceId, callback);
        }

        /// <summary>
        /// 添加Sticky Event
        /// </summary>
        /// <param name="key"></param>
        /// <param name="data"></param>
        /// <param name="scope"></param>
        [Obsolete("该函数已废弃")]
        public void SetStickyEvent(string key, byte[] data, StickyEventScope scope)
        {
            string traceId = Guid.NewGuid().ToString();
            MuninnEvent e = new MuninnEvent()
            {
                SetStickyEventRequest = new SetStickyEventRequest()
                {
                    TraceId = traceId,
                    Key = key,
                    Data = ByteString.CopyFrom(data),
                    Scope = StickyEventScopeConvertor.convert(scope),
                }
            };
            SendMuninnEvent(e);

            // RegisterOperationCallback(MuninnOpActionType.SetStickyEvent, traceId, callback);
        }

        /// <summary>
        /// 添加Sticky Event
        /// </summary>
        /// <param name="key"></param>
        /// <param name="data"></param>
        /// <param name="scope"></param>
        /// <param name="callback"></param>
        public void SetStickyEvent(string key, byte[] data, StickyEventScope scope,
            Action<MuninnSetStickyEventResponse> callback)
        {
            string traceId = Guid.NewGuid().ToString();
            MuninnEvent e = new MuninnEvent()
            {
                SetStickyEventRequest = new SetStickyEventRequest()
                {
                    TraceId = traceId,
                    Key = key,
                    Data = ByteString.CopyFrom(data),
                    Scope = StickyEventScopeConvertor.convert(scope),
                }
            };
            SendMuninnEvent(e);

            RegisterOperationCallback(MuninnOpActionType.SetStickyEvent, traceId, callback);
        }

        /// <summary>
        /// 移除Sticky Event
        /// </summary>
        /// <param name="key"></param>
        /// <param name="scope"></param>
        [Obsolete("该函数已废弃")]
        public void RemoveStickyEvent(string key, StickyEventScope scope)
        {
            string traceId = Guid.NewGuid().ToString();
            MuninnEvent e = new MuninnEvent()
            {
                RemoveStickyEventRequest = new RemoveStickyEventRequest()
                {
                    TraceId = traceId,
                    Key = key,
                    Scope = StickyEventScopeConvertor.convert(scope),
                }
            };
            SendMuninnEvent(e);
        }

        /// <summary>
        /// 移除Sticky Event
        /// </summary>
        /// <param name="key"></param>
        /// <param name="scope"></param>
        public void RemoveStickyEvent(string key, StickyEventScope scope,
            Action<MuninnRemoveStickyEventResponse> callback)
        {
            string traceId = Guid.NewGuid().ToString();
            MuninnEvent e = new MuninnEvent()
            {
                RemoveStickyEventRequest = new RemoveStickyEventRequest()
                {
                    TraceId = traceId,
                    Key = key,
                    Scope = StickyEventScopeConvertor.convert(scope),
                }
            };
            SendMuninnEvent(e);

            RegisterOperationCallback(MuninnOpActionType.RemoveStickyEvent, traceId, callback);
        }

        /// <summary>
        /// 查询Sticky Event
        /// </summary>
        /// <param name="key"></param>
        /// <param name="scope"></param>
        /// <param name="callback"></param>
        public void GetStickyEvent(string key, StickyEventScope scope, Action<MuninnGetStickyEventResponse> callback)
        {
            string traceId = Guid.NewGuid().ToString();
            // *) 先发送
            MuninnEvent e = new MuninnEvent()
            {
                QueryStickyEventRequest = new QueryStickyEventRequest()
                {
                    TraceId = traceId,
                    Key = key,
                    Scope = StickyEventScopeConvertor.convert(scope),
                }
            };
            SendMuninnEvent(e);

            RegisterOperationCallback(MuninnOpActionType.GetStickyEvent, traceId, callback);
        }

        public void KickPlayer(uint senderId)
        {
            string traceId = Guid.NewGuid().ToString();
            MuninnEvent e = new MuninnEvent()
            {
                KickPlayerRequest = new KickPlayerRequest()
                {
                    TraceId = traceId,
                    PlayerId = senderId,
                }
            };
            SendMuninnEvent(e);
        }

        public void UpdatePlayerInfo(MuninnPlayer player, Action<MuninnUpdatePlayerResponse> callback)
        {
            if (player == null)
            {
                Debug.Log("player is nll");
                return;
            }

            string traceId = Guid.NewGuid().ToString();

            // *) 先发送
            MuninnEvent e = new MuninnEvent()
            {
                UpdatePlayerRequest = new UpdatePlayerRequest()
                {
                    TraceId = traceId,
                    PlayerId = player.SenderId,
                    Properties = { },
                }
            };
            if (!string.IsNullOrWhiteSpace(player.Id))
            {
                e.UpdatePlayerRequest.UniqueId = player.Id;
            }

            if (!string.IsNullOrWhiteSpace(player.Name))
            {
                e.UpdatePlayerRequest.Name = player.Name;
            }

            if (player.Properties != null && player.Properties.Count > 0)
            {
                foreach (var item in player.Properties)
                {
                    e.UpdatePlayerRequest.Properties.Add(item.Key, item.Value);
                }
            }

            SendMuninnEvent(e);

            RegisterOperationCallback(MuninnOpActionType.UpdatePlayer, traceId, callback);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="properties"></param>
        /// <param name="callback"></param>
        public void UpdateRoomCustomProperties(Dictionary<string, string> properties,
            Action<MuninnUpdateRoomCustomPropertiesResponse> callback)
        {
            string traceId = Guid.NewGuid().ToString();

            // *) 先发送
            MuninnEvent e = new MuninnEvent()
            {
                UpdateRoomCustomPropertiesRequest = new UpdateRoomCustomPropertiesRequest()
                {
                    TraceId = traceId,
                    Properties = { },
                }
            };

            if (properties != null && properties.Count > 0)
            {
                foreach (var item in properties)
                {
                    e.UpdateRoomCustomPropertiesRequest.Properties.Add(item.Key, item.Value);
                }
            }

            SendMuninnEvent(e);

            RegisterOperationCallback(MuninnOpActionType.UpdateRoomCustomProperties, traceId, callback);
        }


        /// <summary>
        /// 更新服务器UTC时间戳
        /// </summary>
        public void FetchTimestamp()
        {
            var @event = new MuninnEvent
            {
                FetchTimestampRequest = new FetchTimestampRequest()
            };
            _startFetchTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
            SendMuninnEvent(@event);
        }

        /// <summary>
        /// 获取切片后的缓存事件
        /// </summary>
        /// <param name="slice">切片值</param>
        public void GetSlicedCacheEvents(int slice = 0)
        {
            var e = new MuninnEvent
            {
                GetSlicedCacheRequest = new GetSlicedCacheRequest
                {
                    Start = slice
                }
            };

            SendMuninnEvent(e);
        }

        /// <summary>
        /// 向当前切片添加缓存事件
        /// </summary>
        /// <param name="code">事件号，用于适配Photon结构</param>
        /// <param name="data">事件内容</param>
        /// <param name="global">是否要设置为房间全局事件</param>
        public void AddCodedCache(byte code, byte[] data, bool global = true)
        {
            var req = new AddCodedCacheRequest
            {
                Global = global,
                Code = code
            };
            if (data != null)
            {
                req.Data = ByteString.CopyFrom(data);
            }

            var e = new MuninnEvent
            {
                AddCodedCacheRequest = req
            };
            SendMuninnEvent(e);
        }

        /// <summary>
        /// 删除所有切片中的匹配缓存事件
        /// </summary>
        /// <param name="code">事件编号，适配Photon</param>
        /// <param name="data">事件内容</param>
        /// <param name="playerIds">事件发送者的ID集</param>
        public void RemoveCodedCache(byte code, byte[] data, IEnumerable<uint> playerIds)
        {
            var req = new RemoveCodedCacheRequest
            {
                Code = code
            };
            if (data != null)
            {
                req.Data = ByteString.CopyFrom(data);
            }

            if (playerIds != null)
            {
                req.PlayerIds.Add(playerIds);
            }

            var e = new MuninnEvent
            {
                RemoveCodedCacheRequest = req
            };
            SendMuninnEvent(e);
        }

        /// <summary>
        /// 清空失效缓存，包括房间缓存及已退出玩家的缓存
        /// </summary>
        public void ClearInvalidCodedCache()
        {
            var e = new MuninnEvent
            {
                ClearInvalidCodedCacheRequest = new ClearInvalidCodedCacheRequest()
            };
            SendMuninnEvent(e);
        }

        /// <summary>
        /// 操作服务器切片位置
        /// </summary>
        /// <param name="operation">具体操作</param>
        /// <param name="slice">切片参数值</param>
        public void OperateSlice(SliceOperation operation, int slice = 0)
        {
            var e = new MuninnEvent
            {
                OperateSliceRequest = new OperateSliceRequest
                {
                    Operation = operation.ToMessage(),
                    Slice = slice
                }
            };
            SendMuninnEvent(e);
        }

        public void OnAllocRoom(MuninnNetworkEndpoint endpoint)
        {
            // *) 
            if (_muninnClient != null && _muninnClient.IsConnected())
            {
                Debug.LogWarning("client had connected before, so ignore");
                return;
            }

            _muninnNetworkEndpoint = endpoint;

            _muninnClient = MuninnTransportFactoryRegistry.Create(
                MuninnSettings.TransportType, OnConnectedTransport, OnDispatchEvent, OnDisconnectedTransport
            );

            if (_muninnClient == null)
            {
                Debug.LogFormat("transport config not valid");
                return;
            }

            Debug.LogFormat(
                "Room information, roomUuid:{0}, name:{1}, node host:{2}, port:{3}, transport:{4}",
                _muninnNetworkEndpoint.RoomUuid,
                _muninnNetworkEndpoint.Name,
                _muninnNetworkEndpoint.ServerHost,
                _muninnNetworkEndpoint.ServerPort,
                MuninnSettings.TransportType.ToString()
            );

            if (!_muninnClient.Available())
            {
                Debug.LogWarningFormat("Platform don't support transport: {0}", MuninnSettings.TransportType);
                return;
            }

            _muninnClient.Init(_muninnNetworkEndpoint.ServerHost, _muninnNetworkEndpoint.ServerPort);
        }

        private void MuninnUpdate()
        {
            if (_muninnClient == null)
            {
                return;
            }

            if (_muninnClient.IsConnected())
            {
                if (!MuninnSettings.Development && _muninnHeartbeatTimer.IsTimeout())
                {
                    Debug.Log("muninn client heartbeat timeout");
                    OnLeftRoom(new LeaveRoomEvent(LeaveRoomReason.DisconnectByTimeout));
                    _muninnClient?.Disconnect();
                    // OnDisconnectedTransport();
                    return;
                }
            }

            _muninnClient?.Update();
        }

        // 是给Client, 回调用的
        protected virtual void OnConnectedTransport()
        {
            _muninnHeartbeatTimer.Start(MuninnNetwork.Timeout);

            // 填充下，用户的信息
            MuninnEvent eEvent = new MuninnEvent()
            {
                JoinRoomRequest = new JoinRoomRequest()
                {
                    RoomId = _muninnNetworkEndpoint.RoomUuid,
                    UniqueId = MuninnNetwork.PlayerInfo.Id,
                    Name = MuninnNetwork.PlayerInfo.Name,
                    Properties = { },
                    UosAppId = MuninnSettings.UosAppId,
                    Debug = MuninnSettings.Development,
                    JoinCode = string.IsNullOrWhiteSpace(_muninnNetworkEndpoint.JoinCode)
                        ? ""
                        : _muninnNetworkEndpoint.JoinCode,
                }
            };

            // 需要补充下，房间的内容信息, 这边是用户的信息
            if (MuninnNetwork.PlayerInfo.Properties != null && MuninnNetwork.PlayerInfo.Properties.Count > 0)
            {
                foreach (var item in MuninnNetwork.PlayerInfo.Properties)
                {
                    eEvent.JoinRoomRequest.Properties.Add(item.Key, item.Value);
                }
            }

            _muninnClient.SendEvent(eEvent);
        }

        /// <summary>
        /// 传输层层面的回调
        /// </summary>
        protected virtual void OnDisconnectedTransport()
        {
            if (_muninnClient == null) return;

            Debug.Log("On Disconnected!");
            OnDisconnected();
            _muninnClient?.OnDestroy();
            _muninnClient = null;
        }

        public void RaiseEvent(byte[] content, RaiseEventOptions options)
        {
            // groups 
            MuninnEvent e = new MuninnEvent()
            {
                SentMessage = new SentMessage()
                {
                    RaiseEventTarget = RaiseEventTargetConvertor.convert(options.Target),
                    Data = ByteString.CopyFrom(content),
                }
            };

            if (options.TargetGroups != null)
            {
                for (int i = 0; i < options.TargetGroups.Length; i++)
                {
                    e.SentMessage.TargetGroups.Add(options.TargetGroups[i]);
                }
            }

            if (options.ReceiverIds != null)
            {
                for (int i = 0; i < options.ReceiverIds.Length; i++)
                {
                    e.SentMessage.ReceiverIds.Add(options.ReceiverIds[i]);
                }
            }

            SendMuninnEvent(e);
        }

        protected virtual void SendMuninnEvent(MuninnEvent e)
        {
            _muninnClient?.SendEvent(e);
        }

        protected virtual void OnDispatchEvent(MuninnEvent e)
        {
            if (e == null) return;
            if (_muninnClient == null || !_muninnClient.IsConnected()) return;

            _muninnHeartbeatTimer.Refresh();
            switch (e.ContentCase)
            {
                case MuninnEvent.ContentOneofCase.JoinRoomResponse:
                {
                    JoinRoomResponse r = e.JoinRoomResponse;
                    Debug.Log(String.Format("join room response, response id ( current user sender id ) : {0}", r.Id));

                    if (r.Code == 0)
                    {
                        _muninnRoomView = MuninnRoomView.Create(r);
                        OnJoinedRoom(_muninnRoomView);
                    }
                    else
                    {
                        // 加入房间失败
                        // 提取错误码信息
                        MuninnError err = MuninnStatusCodeHelper.Convert(r.Code);
                        OnJoinRoomFailed(err);
                    }

                    break;
                }
                case MuninnEvent.ContentOneofCase.LeaveRoomResponse:
                {
                    Debug.Log("receive a leave room response ack");
                    _muninnRoomView = null;
                    OnLeftRoom(new LeaveRoomEvent(LeaveRoomReason.DisconnectByClient));
                    _muninnClient?.Disconnect();
                    // OnDisconnectedTransport();
                    break;
                }
                case MuninnEvent.ContentOneofCase.PlayerKickedEvent:
                {
                    PlayerKickedEvent ke = e.PlayerKickedEvent;
                    if (ke.Code == (int)MuninnCode.RoomClosed)
                    {
                        // 这边假定，先为关闭房间，会引发这个通知
                        OnLeftRoom(new LeaveRoomEvent(LeaveRoomReason.DisconnectByCloseRoom));
                    }
                    else if (ke.Code == (int)MuninnCode.UserReLoggedIn)
                    {
                        Debug.Log("Same Account Login In Another Place Or Device");
                        OnLeftRoom(new LeaveRoomEvent(LeaveRoomReason.DisconnectBySameAccount));
                    }
                    else if (ke.Code == (int)MuninnCode.KickPlayerByMasterClient)
                    {
                        Debug.Log("Be Kicked By Room Owner");
                        OnLeftRoom(new LeaveRoomEvent(LeaveRoomReason.DisconnectByKick));
                    }
                    else
                    {
                        // 正常的网络断开
                        OnLeftRoom(new LeaveRoomEvent(LeaveRoomReason.DisconnectByClient));
                    }

                    _muninnClient?.Disconnect();

                    // 这个主要是，新旧连接顶替
                    break;
                }
                case MuninnEvent.ContentOneofCase.Ping:
                {
                    MuninnEvent e2 = new MuninnEvent()
                    {
                        Pong = new MuninnPong(),
                    };
                    _muninnClient?.SendEvent(e2);
                    break;
                }
                case MuninnEvent.ContentOneofCase.Pong:
                {
                    // 更新自身的状态信息
                    break;
                }
                case MuninnEvent.ContentOneofCase.ReceivedMessage:
                {
                    ReceivedMessage r = e.ReceivedMessage;
                    // r.GroupIds
                    List<uint> groups = new List<uint>();
                    if (r.GroupIds != null && r.GroupIds.Count > 0)
                    {
                        foreach (var g in r.GroupIds)
                        {
                            groups.Add(g);
                        }
                    }

                    Model.MuninnEvent me = new Model.MuninnEvent()
                    {
                        Data = r.Data.ToByteArray(),
                        GroupIds = groups,
                        SenderId = r.SenderId,
                        Target = RaiseEventTargetConvertor.convert(r.Target),
                    };

                    if (me.Target == RaiseEventTarget.TO_MASTER)
                    {
                        OnServerCall(me);
                    }
                    //  如果是自己发给群组且群组里包括自己的事件，则忽略
                    else if (me.Target != RaiseEventTarget.TO_GROUPS || me.SenderId != _muninnRoomView.SenderId)
                    {
                        OnEvent(me);
                    }

                    break;
                }
                case MuninnEvent.ContentOneofCase.PlayerEnteredRoomEvent:
                {
                    // 有新玩家，加入房间
                    PlayerEnteredRoomEvent r = e.PlayerEnteredRoomEvent;
                    MuninnPlayer player = MuninnPlayer.toModel(r.Player);
                    MuninnRoomView.AddPlayer(_muninnRoomView, player);
                    OnPlayerEnteredRoom(player);
                    break;
                }
                case MuninnEvent.ContentOneofCase.PlayerLeftRoomEvent:
                {
                    // 有玩家，离开房间
                    PlayerLeftRoomEvent r = e.PlayerLeftRoomEvent;
                    MuninnPlayer player = MuninnPlayer.toModel(r.Player);
                    MuninnRoomView.RemovePlayer(_muninnRoomView, player);
                    OnPlayerLeftRoom(player);
                    break;
                }
                case MuninnEvent.ContentOneofCase.SubscribeGroupsResponse:
                {
                    // 订阅interest group
                    SubscribeGroupsResponse r = e.SubscribeGroupsResponse;
                    if (r.Code != 0)
                    {
                        MuninnError err = MuninnStatusCodeHelper.Convert(r.Code);
                        OnSubscribeGroupsFailed(err);
                    }
                    else
                    {
                        Debug.Log("subscribe successfully");
                        MuninnSubscribeGroupResponse resp = MuninnSubscribeGroupResponse.Create(r);
                        MuninnRoomView.SubscribeGroup(_muninnRoomView, resp);
                        OnSubscribeGroups(resp);
                    }

                    break;
                }
                case MuninnEvent.ContentOneofCase.UnsubscribeGroupsResponse:
                {
                    // 取消订阅interest group
                    UnsubscribeGroupsResponse r = e.UnsubscribeGroupsResponse;
                    if (r.Code != 0)
                    {
                        MuninnError err = MuninnStatusCodeHelper.Convert(r.Code);
                        OnUnsubscribeGroupsFailed(err);
                    }
                    else
                    {
                        Debug.Log("unsubscribe successfully");
                        MuninnUnsubscribeGroupsResponse resp = MuninnUnsubscribeGroupsResponse.Create(r);
                        MuninnRoomView.UnsubscribeGroup(_muninnRoomView, resp);
                        OnUnsubscribeGroups(resp);
                    }

                    break;
                }
                case MuninnEvent.ContentOneofCase.AddCachedEventResponse:
                {
                    Debug.Log("receive add cached event response");
                    AddCachedEventResponse r = e.AddCachedEventResponse;

                    string traceId = r.TraceId;
                    Action<MuninnAddCachedEventResponse> callback =
                        (Action<MuninnAddCachedEventResponse>)GetThenRemoveOperationCallback(
                            MuninnOpActionType.AddCachedEvent, traceId);

                    MuninnAddCachedEventResponse response = MuninnAddCachedEventResponse.Create(r);
                    if (response.Code == (uint)MuninnCode.OK)
                    {
                        // MuninnRoomView.AddStickyEvent(_muninnRoomView, response);
                    }

                    callback?.Invoke(response);

                    // if (r.Code != 0)
                    // {
                    //     // 这边回调，添加stickyEvent失败
                    //     MuninnError err = MuninnStatusCodeHelper.Convert(r.Code);
                    //     OnAddCachedEventFailed(err);
                    // }
                    // else
                    // {
                    //     Debug.Log("add cached event successfully");
                    //     MuninnAddCachedEventResponse resp = MuninnAddCachedEventResponse.Create(r);
                    //     // MuninnRoomView.AddStickyEvent(_muninnRoomView, resp);
                    //     OnAddCachedEvent(resp);
                    // }
                    break;
                }
                case MuninnEvent.ContentOneofCase.RemoveCachedEventResponse:
                {
                    Debug.Log("receive remove cached event response");
                    RemoveCachedEventResponse r = e.RemoveCachedEventResponse;

                    string traceId = r.TraceId;
                    Action<MuninnRemoveCachedEventResponse> callback =
                        (Action<MuninnRemoveCachedEventResponse>)GetThenRemoveOperationCallback(
                            MuninnOpActionType.RemoveCachedEvent, traceId);

                    MuninnRemoveCachedEventResponse response = MuninnRemoveCachedEventResponse.Create(r);
                    if (response.Code == (uint)MuninnCode.OK)
                    {
                        // MuninnRoomView.AddStickyEvent(_muninnRoomView, response);
                    }

                    callback?.Invoke(response);
                    break;
                }
                case MuninnEvent.ContentOneofCase.SetStickyEventResponse:
                {
                    SetStickyEventResponse r = e.SetStickyEventResponse;
                    string traceId = r.TraceId;
                    Action<MuninnSetStickyEventResponse> callback =
                        (Action<MuninnSetStickyEventResponse>)GetThenRemoveOperationCallback(
                            MuninnOpActionType.SetStickyEvent, traceId);

                    MuninnSetStickyEventResponse response = MuninnSetStickyEventResponse.Create(r);
                    if (response.Code == (uint)MuninnCode.OK)
                    {
                        MuninnRoomView.AddStickyEvent(_muninnRoomView, response);
                    }

                    callback?.Invoke(response);

                    break;
                }
                case MuninnEvent.ContentOneofCase.RemoveStickyEventResponse:
                {
                    RemoveStickyEventResponse r = e.RemoveStickyEventResponse;
                    string traceId = r.TraceId;
                    Action<MuninnRemoveStickyEventResponse> callback =
                        (Action<MuninnRemoveStickyEventResponse>)GetThenRemoveOperationCallback(
                            MuninnOpActionType.RemoveStickyEvent, traceId);

                    MuninnRemoveStickyEventResponse response = MuninnRemoveStickyEventResponse.Create(r);
                    if (response.Code == (uint)MuninnCode.OK)
                    {
                        MuninnRoomView.RemoveStickyEvent(_muninnRoomView, response);
                    }

                    callback?.Invoke(response);
                    break;
                }
                case MuninnEvent.ContentOneofCase.QueryStickyEventResponse:
                {
                    QueryStickyEventResponse r = e.QueryStickyEventResponse;

                    string traceId = r.TraceId;
                    Action<MuninnGetStickyEventResponse> callback =
                        (Action<MuninnGetStickyEventResponse>)GetThenRemoveOperationCallback(
                            MuninnOpActionType.GetStickyEvent, traceId);

                    MuninnGetStickyEventResponse response = MuninnGetStickyEventResponse.Create(r);
                    callback?.Invoke(response);
                    break;
                }
                case MuninnEvent.ContentOneofCase.MigrateMasterClientEvent:
                {
                    MigrateMasterClientEvent r = e.MigrateMasterClientEvent;
                    MuninnRoomView.ChangeMasterClientId(_muninnRoomView, r.MasterClientId);
                    OnMasterClientChanged(r.MasterClientId);
                    break;
                }
                case MuninnEvent.ContentOneofCase.KickPlayerResponse:
                {
                    KickPlayerResponse r = e.KickPlayerResponse;
                    if (r.Code == (uint)MuninnCode.OK)
                    {
                        MuninnKickPlayerResponse response = MuninnKickPlayerResponse.Create(r);
                        OnKickedPlayer(response);
                    }
                    else
                    {
                        MuninnError err = MuninnStatusCodeHelper.Convert(r.Code);
                        OnKickPlayerFailed(err);
                    }

                    break;
                }
                case MuninnEvent.ContentOneofCase.UpdatePlayerResponse:
                {
                    UpdatePlayerResponse r = e.UpdatePlayerResponse;
                    if (r.Code == (uint)MuninnCode.OK)
                    {
                        MuninnRoomView.UpdatePlayer(GetMuninnRoomView(), MuninnPlayer.toModel(r.Player));
                    }

                    string traceId = r.TraceId;
                    Action<MuninnUpdatePlayerResponse> callback = (Action<MuninnUpdatePlayerResponse>)
                        GetThenRemoveOperationCallback(MuninnOpActionType.UpdatePlayer, traceId);

                    MuninnUpdatePlayerResponse response = MuninnUpdatePlayerResponse.Create(r);
                    callback?.Invoke(response);
                    break;
                }
                case MuninnEvent.ContentOneofCase.PlayerUpdatedEvent:
                {
                    PlayerUpdatedEvent evt = e.PlayerUpdatedEvent;
                    if (evt.Player != null)
                    {
                        MuninnRoomView.UpdatePlayer(GetMuninnRoomView(), MuninnPlayer.toModel(evt.Player));
                        OnPlayerInfoUpdated(MuninnPlayer.toModel(evt.Player));
                    }

                    break;
                }
                case MuninnEvent.ContentOneofCase.UpdateRoomCustomPropertiesResponse:
                {
                    UpdateRoomCustomPropertiesResponse r = e.UpdateRoomCustomPropertiesResponse;
                    if (r.Code == (uint)MuninnCode.OK)
                    {
                        Dictionary<string, string> dict = new Dictionary<string, string>();
                        foreach (var kv in r.Properties)
                        {
                            dict.Add(kv.Key, kv.Value);
                        }

                        MuninnRoomView.UpdateRoomCustomProperties(GetMuninnRoomView(), dict);
                    }

                    string traceId = r.TraceId;
                    Action<MuninnUpdateRoomCustomPropertiesResponse> callback =
                        (Action<MuninnUpdateRoomCustomPropertiesResponse>)
                        GetThenRemoveOperationCallback(MuninnOpActionType.UpdateRoomCustomProperties, traceId);

                    MuninnUpdateRoomCustomPropertiesResponse response =
                        MuninnUpdateRoomCustomPropertiesResponse.Create(r);
                    callback?.Invoke(response);
                    break;
                }
                case MuninnEvent.ContentOneofCase.RoomCustomPropertiesUpdatedEvent:
                {
                    RoomCustomPropertiesUpdatedEvent evt = e.RoomCustomPropertiesUpdatedEvent;

                    Dictionary<string, string> customProperties = new Dictionary<string, string>();
                    if (evt.Properties != null && evt.Properties.Count > 0)
                    {
                        foreach (var kv in evt.Properties)
                        {
                            customProperties.Add(kv.Key, kv.Value);
                        }
                    }

                    MuninnRoomView.UpdateRoomCustomProperties(GetMuninnRoomView(), customProperties);
                    OnRoomCustomPropertiesUpdated(customProperties);
                    break;
                }
                // 获取服务器时间戳
                case MuninnEvent.ContentOneofCase.FetchTimestampResponse:
                {
                    var endFetchTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
                    var serverTimestamp = e.FetchTimestampResponse.Timestamp;
                    var rttTime = (endFetchTime - _startFetchTime) / 2;
                    ServerTimeDelta = serverTimestamp + rttTime - endFetchTime;
                    break;
                }
                // 服务端缓存切片修改事件
                case MuninnEvent.ContentOneofCase.CacheSliceChangedEvent:
                {
                    var evt = e.CacheSliceChangedEvent;
                    OnCacheSliceChanged(evt.Slice, evt.SenderId);
                    break;
                }
                // 加入房间时获取切片后的缓存事件
                case MuninnEvent.ContentOneofCase.GetSlicedCacheResponse:
                {
                    var resp = e.GetSlicedCacheResponse;
                    var result = new SortedDictionary<int, IEnumerable<CodedEvent>>();
                    foreach (var slicedCodedEvents in resp.Events)
                    {
                        result.Add(slicedCodedEvents.Slice,
                            slicedCodedEvents.Events.Select(@event => @event.ToModel()));
                    }

                    OnSlicedCacheReceived(result);
                    break;
                }
            }
        }
    }
}