using System;
using System.Collections.Generic;
using XGame.Framework.Interfaces;

namespace XGame.Framework.UI.View
{
    internal class UIControllerGroup : IUIControllerGroup
    {
        protected UIContext _context;
        private IUIViewModel _viewModel;
        private List<IUIController> _controllers;
        private List<IUpdate> _updates;
        private List<ILateUpdate> _lateUpdates;
        public UIControllerGroup(UIContext context, IUIViewModel viewModel)
        {
            _context = context;
            _viewModel = viewModel;
            _controllers = new List<IUIController>();
            _updates = new List<IUpdate>();
            _lateUpdates = new List<ILateUpdate>();
        }

        public void AddController(IUIController controller)
        {
            _controllers.Add(controller);
            if (controller is IUIContextSetter contextSetter)
            {
                contextSetter.Context = _context;
            }
            if (controller is IUIViewModelSetter vmSetter)
            {
                vmSetter.ViewModel = _viewModel;
            }
            if (controller is IUpdate update)
            {
                _updates.Add(update);
            }
            if (controller is ILateUpdate lateUpdate)
            {
                _lateUpdates.Add(lateUpdate);
            }
        }

        #region public
        public void Enable(object intent)
        {
            foreach (var controller in _controllers)
            {
                controller?.OnEnable(intent);
            }
        }
        public void Disable()
        {
            foreach (var controller in _controllers)
            {
                controller?.OnDisable();
            }
        }
        public void Update(int millisecond)
        {
            foreach (var update in _updates)
            {
                update?.Update(millisecond);
            }
        }
        public void LateUpdate(int millisecond)
        {
            foreach (var lateUpdate in _lateUpdates)
            {
                lateUpdate?.LateUpdate(millisecond);
            }
        }
        public void Dispose()
        {
            _updates.Clear();
            _lateUpdates.Clear();
            foreach(var controller in _controllers)
            {
                (controller as IDisposable)?.Dispose();
            }
            _controllers.Clear();
        }
        #endregion
    }
}
