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

namespace XGame.Framework.Map
{
    internal class EntityControllerGroup : IEntityControllerGroup
    {
        protected MapContext _context;
        private IEntityViewModel _viewModel;
        private List<IEntityController> _controllers;
        private List<IUpdate> _updates;
        private List<ILateUpdate> _lateUpdates;

        public EntityControllerGroup(MapContext context, IEntityViewModel viewModel)
        {
            _context = context;
            _viewModel = viewModel;
            _controllers = new List<IEntityController>();
            _updates = new List<IUpdate>();
            _lateUpdates = new List<ILateUpdate>();
        }

        public void AddController(IEntityController controller)
        {
            _controllers.Add(controller);
            if (controller is IMapContextSetter contextSetter)
            {
                contextSetter.Context = _context;
            }
            if (controller is IEntityViewModelSetter 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
    }
}