using Thousandto.Code.Center;
using Thousandto.Code.Global;
using Thousandto.CoreSDK;
using Thousandto.CoreSDK.Event;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EventManager = UnityEngine.Gonbest.MagicCube.EventManager;
using EventSystemHandler = UnityEngine.Gonbest.MagicCube.EventSystemHandler;
using JSONData = UnityEngine.Gonbest.MagicCube.JSONData;
using EventConstDefine = UnityEngine.Gonbest.MagicCube.EventConstDefine;
using JSONArray = UnityEngine.Gonbest.MagicCube.JSONArray;

namespace Thousandto.Code.Logic
{
    //基础协议
    public class BaseVoiceLogic
    {
        #region//静态变量
        //当前激活的逻辑
        public static BaseVoiceLogic ActiveVoiceLogic = null;
        //玩家控制是否可以说话 -- 
        private static bool _userIsMute = false;
        #endregion

        #region//私有变量
        private ulong _id = 0;
        //通道ID
        private string _channelID = string.Empty;
        //系统控制是否说话
        private bool _systemIsMute = true;
       
        //所有玩家
        private List<string> _allUsers = new List<string>();
        //玩家数量
        private int _userCount = 0;
        //是否激活
        private bool _isInRoom = false;
        #endregion

        #region
        //当前频道类型
        public VoiceChannel Channel { get; protected set; }
        //当前频道ID
        public ulong ID {

            get { return _id; }
            protected set {
                if (_id != value)
                {
                    _id = value;
                    _channelID = string.Format(Channel.ToString() + "_" + _id);
                }
            }
        }

        //当前频道所有玩家的列表
        public List<string> AllUsers
        {
            get
            {
                return _allUsers;
            }
        }
        //玩家数量
        public int UserCount
        {
            get
            {
                return _userCount;
            }
        }
        
        //是否被激活
        public bool IsActived
        {
            get
            {
                return _isInRoom;
            }
        }

        //系统控制是否静音
        public bool SystemIsMute
        {
            get
            {
                return _systemIsMute;
            }
            set
            {
                if (_systemIsMute != value)
                {
                    _systemIsMute = value;
                    OnMuteChanged();
                }
            }
        }
        //玩家自定义是否静音
        public bool UserIsMute
        {
            get
            {
                return _userIsMute;
            }
            set
            {
                if (_userIsMute != value)
                {
                    _userIsMute = value;
                    OnMuteChanged();
                }
            }
        }
        #endregion

        #region//公共方法
        protected BaseVoiceLogic(VoiceChannel channel)
        {
            Channel = channel;            
        }

        public void Initialize()
        {
            //注册玩家信息改变的消息
            EventManager.SharedInstance.RegFixEventHandle(SDKEventDefine.SDK_VOICE_ENTER, OnUserEnterSuccessCallBack);
            EventManager.SharedInstance.RegFixEventHandle(SDKEventDefine.SDK_VOICE_ROOM_ENTER_FAIL, OnUserEnterFailCallBack);
            EventManager.SharedInstance.RegFixEventHandle(SDKEventDefine.SDK_VOICE_ROOM_PERSON_NUM, OnUserListChangedCallBack);
            EventManager.SharedInstance.RegFixEventHandle(SDKEventDefine.SDK_VOICE_EXIT, OnUserExitCallBack);          
            OnInitialize();
        }

        public void Uninitialize()
        {
            //卸载玩家信息改变的消息
            EventManager.SharedInstance.UnRegFixEventHandle(SDKEventDefine.SDK_VOICE_ENTER, OnUserEnterSuccessCallBack);
            EventManager.SharedInstance.UnRegFixEventHandle(SDKEventDefine.SDK_VOICE_ROOM_ENTER_FAIL, OnUserEnterFailCallBack);
            EventManager.SharedInstance.UnRegFixEventHandle(SDKEventDefine.SDK_VOICE_ROOM_PERSON_NUM, OnUserListChangedCallBack);
            EventManager.SharedInstance.UnRegFixEventHandle(SDKEventDefine.SDK_VOICE_EXIT, OnUserExitCallBack);

            Exit();
            ClearUsers();
            SystemIsMute = true;            
            OnUninitialize();
        }

        public void Enter()
        {
            if (ActiveVoiceLogic != null)
            {
                ActiveVoiceLogic.Exit();
            }

            if (OnEnter())
            {
                ActiveVoiceLogic = this;               
            }
            else
            {
                ActiveVoiceLogic = null;             
            }
            
        }

        public void Exit()
        {           
            OnExit();
            ActiveVoiceLogic = null;

        }
        #endregion

        #region//保护类型--用于子类调用
        protected void EnterOfSDK()
        {
            //FuncellThirdVoiceSDK.Instance.JoinVoiceRoom(LocalPlayerRoot.LocalPlayerID.ToString(), _channelID, "1", "0");
        }

        protected void ExitOfSDK()
        {
            //FuncellThirdVoiceSDK.Instance.LeaveRoom();
        }

        public void QueryUserListOfSDK()
        {
            //var obj = FuncellThirdVoiceSDK.Instance.CallQueryUserList(_channelID);
            //ParseUserListJson(obj as string);
        }

        protected void ClearUsers()
        {
            _allUsers.Clear();
            _userCount = 0;
            //ToDo:这里需要发送一个用户数量改变的消息
            GameCenter.EventManager.PushFixEvent((int)LogicEventDefine.EID_EVENT_VOICE_MEMBERINFO_CHANGED,this);
        }

       
        #endregion

        #region//子类继承,重写
        protected virtual void OnInitialize()
        {

        }

        protected virtual void OnUninitialize()
        {

        }

        protected virtual bool OnEnter()
        {
            return true;
        }
        protected virtual bool OnExit()
        {
            return true;
        }
        #endregion

        #region//私有方法

        //玩家进入房间的回调
        private void OnUserEnterSuccessCallBack(object obj,object sender)
        {
            string[] arr = obj as string[];
            if (arr[0] == _channelID && ActiveVoiceLogic == this)
            {   
                _isInRoom = true;
                OnMuteChanged();//在进入房间之后进行设置
                //FuncellThirdVoiceSDK.Instance.CallQueryUserList(arr[0]);
                GameCenter.PushFixEvent(LogicEventDefine.EID_EVENT_VOICE_CHANNEL_CHANGED);
            }
        }
        private void OnUserEnterFailCallBack(object obj, object sender)
        {
            string[] arr = obj as string[];
            if (arr[0] == _channelID && ActiveVoiceLogic == this)
            {  
                _isInRoom = false;
                GameCenter.PushFixEvent(LogicEventDefine.EID_EVENT_VOICE_CHANNEL_CHANGED);               
            }
        }

        private void OnUserExitCallBack(object obj, object sender)
        {
            
            //退出不做处理
            _isInRoom = false;
            _id = 0;
            _channelID = string.Empty;
            GameCenter.PushFixEvent(LogicEventDefine.EID_EVENT_VOICE_CHANNEL_CHANGED);
        }

        //当用户列表改变的时候
        private void OnUserListChangedCallBack(object obj, object sender)
        {
            object[] arr = obj as object[];
            if (arr != null && arr.Length >= 3)
            {
                var id = (string)arr[0];
                if (id == _channelID)
                {
                    var users = arr[1] as JSONArray;
                    var status = (int)arr[2];

                    if (status == 0)
                    {//等于0表示是返回全部
                        _allUsers.Clear();
                    }

                    if (status <= 1)
                    {//1是返回进入的用户列表
                        for (int i = 0; i < users.Count; i++)
                        {
                            _allUsers.Add(users[i]);
                        }
                    }
                    else
                    {//2返回的是退出的用户列表
                        for (int i = 0; i < users.Count; i++)
                        {
                            _allUsers.Remove(users[i]);
                        }
                    }
                    _userCount = _allUsers.Count;
                    GameCenter.PushFixEvent(LogicEventDefine.EID_EVENT_VOICE_MEMBERINFO_CHANGED);
                }
            }
            else
            {
                //UnityEngine.Debug.LogError("OnUserListChangedCallBack:返回的obj参数不对." + (arr == null ? "arr == NULL" :("arr.length == "+arr.Length.ToString())));
            }
        }

        //当已经设置改变的时候调用
        private void OnMuteChanged()
        {
            if (_isInRoom)
            {
                //发送给SDK用来设置自己可以说话. 
                //FuncellThirdVoiceSDK.Instance.SetMicrophoneMute(SystemIsMute || UserIsMute);
            }
        }

        //解释用户列表的json串
        private void ParseUserListJson(string jsonText)
        {
            if (jsonText == null)
            {
                //UnityEngine.Debug.LogError("request voice room member list fail !!!!");
                return;
            }

            JSONData json = new JSONData(jsonText);
            if (json == null || json.Count == 0) return;

            _userCount = json.Count;
            //ToDo:这里需要发送一个用户数量改变的消息
            GameCenter.EventManager.PushFixEvent((int)LogicEventDefine.EID_EVENT_VOICE_MEMBERINFO_CHANGED, this);
        }
        #endregion

    }
}