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

namespace XGame.Framework.Nodes
{
    /// <summary>
    /// 业务集合
    /// 主要用于实现业务的Enable、Update、LateUpdate、Load、Unload操作
    /// </summary>
    public class NodeComponentGroup : INodeComponentGroup, ILoadAsyncHandle
    {
        private List<INodeComponent> _components;
        private List<IUpdate> _updates;
        private List<ILateUpdate> _lateUpdates;
        protected NodeContext _context;

        public NodeComponentGroup(NodeContext context)
        {
            _context = context;
            _components = new List<INodeComponent>();
            _updates = new List<IUpdate>();
            _lateUpdates = new List<ILateUpdate>();
        }
        #region 接口实现
        public void Add(INodeComponent component)
        {
            _components.Add(component);
            component.Bind(_context);
            if (component is IUpdate update)
            {
                _updates.Add(update);
            }
            if (component is ILateUpdate lateUpdate)
            {
                _lateUpdates.Add(lateUpdate);
            }
        }
        #endregion
        #region public
        public void Enable(object intent)
        {
            foreach(var component in _components)
            {
                component?.OnEnable(intent);
            }
        }
        public void Disable()
        {
            foreach(var component in _components)
            {
                component?.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()
        {
            foreach (var component in _components)
            {
                (component as IDisposable)?.Dispose();
            }
        }
        #endregion
        public void OnLoadAsync(IAsyncGroup group)
        {
            foreach(var component in _components)
            {
                (component as ILoadAsyncHandle)?.OnLoadAsync(group);
            }
        }
        public void OnUnloadAsync(IAsyncGroup group)
        {
            foreach(var component in _components)
            {
                (component as ILoadAsyncHandle)?.OnUnloadAsync(group);
            }
        }
    }
}
