using System;
using System.Collections.Generic;

namespace WS
{
    ///<summary>网络消息 观察者</summary>
    public class NetworkEvent : WSComponent
    {
        public Dictionary<byte, List<Action<IProto>>> AllAction = new Dictionary<byte, List<Action<IProto>>>();


        /// <summary>添加监听</summary>
        public void AddEvent(byte key, Action<IProto> action)
        {
            if (AllAction.ContainsKey(key))
            {
                AllAction[key].Add(action);
            }
            else
            {
                List<Action<IProto>> listaction = new List<Action<IProto>>();
                listaction.Add(action);
                AllAction[key] = listaction;
            }
        }

        /// <summary>移除监听</summary>
        public void RemoveEventListener(byte key, Action<IProto> action)
        {
            if (AllAction.ContainsKey(key))
            {
                List<Action<IProto>> listaction = AllAction[key];
                listaction.Remove(action);
                if (listaction.Count == 0)
                {
                    AllAction.Remove(key);
                }
            }
        }

        /// <summary>派发</summary>
        public void Dispatch(byte key, IProto proto)
        {
            if (AllAction.ContainsKey(key))
            {
                List<Action<IProto>> listaction = AllAction[key];
                if (listaction != null && listaction.Count > 0)
                {
                    for (int i = 0; i < listaction.Count; i++)
                    {
                        listaction[i]?.Invoke(proto);
                    }
                }
            }
        }

        public override void Dispose()
        {
            base.Dispose();
            foreach (var item in AllAction)
            {
                List<Action<IProto>> listaction = AllAction[item.Key];
                for (int i = 0; i < listaction.Count; i++)
                {
                    listaction[i] = null;
                }
                listaction.Clear();
            }
            AllAction.Clear();
        }
    }
}