using System;

namespace XGame.Framework.UI
{
    /// <summary>
    /// UIView
    /// </summary>
    public abstract partial class UIView : IUIView, IDisposable
    {
        public UIContext Context { get; private set; }
        
        private IUIPanel _panel;
        private IUIViewModel _viewModel;
        private UIControllerGroup _ctrlGroup;
        
        public void Init(UIContext context, IUIPanel panel)
        {
            Context = context;
            _panel = panel;
            _viewModel = CreateViewModel();
            // vm初始化时构建Nested时需要用到Group对象
            _ctrlGroup = new UIControllerGroup(context, _viewModel);
            (context as IUIViewAdapter).CtrlGroup = _ctrlGroup;
            (_viewModel as IUIVMInitable)?.Init(panel, context);
            AddController(_ctrlGroup);
        }
        #region 接口实现
        IUIPanel IUIView.Panel => _panel;
        public bool Active { get; private set; }
        void IUIView.Enable(object intent)
        {
            if (Active) return;
            Active = true;
            _panel.SetActive(true);
            _ctrlGroup.Enable(intent);
        }
        void IUIView.Disable()
        {
            if (!Active) return;
            Active = false;
            _panel.SetActive(false);
            _ctrlGroup.Disable();
            Context.Clear();
        }

        public void Update(int millisecond)
        {
            if (!Active) return;
            _ctrlGroup.Update(millisecond);
        }

        public void LateUpdate(int millisecond)
        {
            if (!Active) return;
            _ctrlGroup.LateUpdate(millisecond);
        }

        void IDisposable.Dispose()
        {
            OnDispose();
            _ctrlGroup.Dispose();
            _panel = null;
            (Context as IDisposable)?.Dispose();
            Context = null;
            _viewModel = null;
        }
        #endregion
        protected abstract void AddController(IUIControllerGroup group);
        protected abstract IUIViewModel CreateViewModel();
        protected abstract void OnDispose();


    }
}

