using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

namespace Rokid.MRC
{
    public class UIServerPanel : UIPanelBase
    {
        public enum SubPanel
        {
            None,
            DescriptionView,
            IPListView,
        }

        private GameObject clientListView;
        private RectTransform clientItemParent;
        private GameObject clientItemPrefab;

        private GameObject descView;
        private Text txtDesc;

        private Button btnIPList;

        private Text txtTips;

        private List<GameObject> ipItemList = new List<GameObject>();

        private Button btnInterface;
        private GameObject interfaceInfo;
        private Text txtInterfaceInfo;

        private Button btnDebug;
        private GameObject debugInfo;
        private Text txtDebugInfo;

        private Button btnObj;
        private Button btnRandomPos;

        public GameObject syncObj;

        public override void OnInit()
        {
            descView = transform.Find("DescView").gameObject;
            txtDesc = transform.Find("DescView/TxtDesc").GetComponent<Text>();

            clientListView = transform.Find("ClientScrollView").gameObject;
            clientItemParent = transform.Find("ClientScrollView/Viewport/Content").GetComponent<RectTransform>();
            clientItemPrefab = transform.Find("ClientScrollView/Viewport/Content/ClientItem").gameObject;
            clientItemPrefab.SetActive(false);

            txtTips = transform.Find("TxtTips").GetComponent<Text>();

            btnIPList = transform.Find("BtnIPList").GetComponent<Button>();
            btnIPList.onClick.AddListener(OnClickOpenIPListView);

            //IP信息
            btnInterface = transform.Find("InterfaceView/BtnOpenInterface").GetComponent<Button>();
            btnInterface.onClick.AddListener(() =>
            {
                interfaceInfo.SetActive(!interfaceInfo.activeSelf);
                RefreshNetworkInfo();
            });
            interfaceInfo = transform.Find("InterfaceView/InterfaceInfo").gameObject;
            interfaceInfo.SetActive(false);
            txtInterfaceInfo = interfaceInfo.transform.Find("TxtInfo").GetComponent<Text>();

            //调试信息
            btnDebug = transform.Find("DebugView/BtnInfo").GetComponent<Button>();
            btnDebug.onClick.AddListener(() =>
            {
                debugInfo.SetActive(!debugInfo.activeSelf);
            });
            debugInfo = transform.Find("DebugView/DebugInfo").gameObject;
            debugInfo.SetActive(false);
            txtDebugInfo = debugInfo.transform.Find("TxtInfo").GetComponent<Text>();

            //生成物体
            btnObj = transform.Find("BtnObj").GetComponent<Button>();
            btnObj.onClick.AddListener(() =>
            {
                if(syncObj == null)
                {
                //syncObj = ResourceManager.Instance.CreateSyncObj();
            }
            });

            //测试，随机移动模型位置
            btnRandomPos = transform.Find("BtnPos").GetComponent<Button>();
            btnRandomPos.onClick.AddListener(() =>
            {
                if(syncObj != null)
                {
                    float delta = Random.Range(0, 0.5f);
                    Vector3 pos = new Vector3(syncObj.transform.position.x + delta, syncObj.transform.position.y, syncObj.transform.position.z + delta);
                    syncObj.transform.position = pos;
                }
            });

            //界面类型
            Canvas canvas = GetComponent<Canvas>();
            if(is3DPanel)
            {
                canvas.renderMode = RenderMode.WorldSpace;
            }
            else
            {
                canvas.renderMode = RenderMode.ScreenSpaceOverlay;
            }
        }

        public override void OnOpen()
        {
            base.OnOpen();

            ClientData.onClientDataUpdate += UpdateIPItem;

            ShowSubView(SubPanel.None);

            txtTips.gameObject.SetActive(false);

            RefreshNetworkInfo();
        }

        private void Update()
        {
            if(!debugInfo.activeSelf)
            {
                return;
            }

            txtDebugInfo.text = $"Camera \n Pos : {Camera.main.transform.position} \n Rot : {Camera.main.transform.rotation}";
        }

        public override void OnClose()
        {
            base.OnClose();

            ClientData.onClientDataUpdate -= UpdateIPItem;
        }

        private void RefreshNetworkInfo()
        {
            string infos = "";
            List<string> interfaceInfos = MRCUtility.GetLocalIP(AddressType.IPv4);
            foreach(var info in interfaceInfos)
            {
                infos += info + "\n";
            }
            txtInterfaceInfo.text = infos;
        }

        private void OnClickOpenIPListView()
        {
            if(clientListView.activeSelf)
            {
                ShowSubView(SubPanel.None);
            }
            else
            {
                ShowSubView(SubPanel.IPListView);
            }
        }

        private void CheckClientList()
        {
            if(ClientData.clientIPList.Count > 0)
            {
                ShowSubView(SubPanel.IPListView);
            }
        }

        public void ShowDesc(string desc)
        {
            ShowSubView(SubPanel.DescriptionView);
            txtDesc.text = desc;
        }

        public void ShowTips(string tips)
        {
            txtTips.gameObject.SetActive(true);
            txtTips.text = tips;

            UIManager.Instance.StartCoroutine(WaitAndClose());
        }

        IEnumerator WaitAndClose()
        {
            yield return new WaitForSeconds(1);
            txtTips.gameObject.SetActive(false);
        }

        public void ShowSubView(SubPanel subPanel)
        {
            switch(subPanel)
            {
                case SubPanel.DescriptionView:
                    clientListView.SetActive(false);
                    descView.SetActive(true);
                    break;
                case SubPanel.IPListView:
                    clientListView.SetActive(true);
                    descView.SetActive(false);
                    break;
                case SubPanel.None:
                    clientListView.SetActive(false);
                    descView.SetActive(false);
                    break;
                default:
                    break;
            }
        }

        private void UpdateIPItem()
        {
            CheckClientList();

            DeleteCachedItem();

            for(int i = 0;i < ClientData.clientIPList.Count;i++)
            {
                ulong ip = ClientData.clientIPList[i];
                AddIPItem(ip);
            }

            LayoutRebuilder.ForceRebuildLayoutImmediate(clientItemParent);
        }

        private void AddIPItem(ulong ip)
        {
            GameObject objItem = Instantiate(clientItemPrefab, clientItemParent);

            ipItemList.Add(objItem);
            Text textIP = objItem.transform.Find("TxtIP").GetComponent<Text>();

            objItem.SetActive(true);

            textIP.text = "UserID : " + ip;
        }

        private void DeleteCachedItem()
        {
            foreach(GameObject ipItem in ipItemList)
            {
                if(ipItem != null)
                {
                    Destroy(ipItem);
                }
            }

            ipItemList.Clear();
        }
    }
}