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

namespace XGame.Framework.UI
{
    /// <summary>
    /// UGUI的实现
    /// </summary>
    public class UITree : MonoBehaviour, IUITree, IDisposable
    {
        [SerializeField]
        private UILayerBehaviour _sample;
        [SerializeField]
        private Camera _uiCamera;

        private Dictionary<UILayer, UILayerBehaviour> _layerBehaviourMap = new Dictionary<UILayer, UILayerBehaviour>();

        private void Start()
        {
            InitLayers();
        }
        private void InitLayers()
        {
            Assert.IsNotNull(_sample);
            var layerVals = Enum.GetValues(typeof(UILayer));
            for (int i = 0; i < layerVals.Length; i++)
            {
                var layer = (UILayer)layerVals.GetValue(i);
                var behaviour = Instantiate(_sample);
                behaviour.transform.SetParent(transform, false);
                behaviour.Layer = layer;
                behaviour.gameObject.SetActive(true);
                _layerBehaviourMap[layer] = behaviour;
            }
        }
        #region 接口实现
        public Camera Camera => _uiCamera;
        public Canvas GetCanvas(UILayer layer)
        {
            var layerBehaviour = _layerBehaviourMap[layer];
            return layerBehaviour.UiCanvas;
        }
        public void AddPanel(IUIPanel panel)
        {
            var layerBehaviour = _layerBehaviourMap[panel.Layer];
            layerBehaviour.AddPanel(panel);
        }
        public void SetAsLastSibling(IUIPanel panel)
        {
            (panel as UIPanel).transform.SetAsLastSibling();
        }
        public void RemovePanel(IUIPanel panel)
        {
            var layerBehaviour = _layerBehaviourMap[panel.Layer];
            layerBehaviour.RemovePanel(panel);
        }

        void IDisposable.Dispose()
        {
            GameObject.Destroy(gameObject);
        }
        #endregion
    }
}
