using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;

/// <summary>
/// 消息发布订阅(非线程安全)
/// </summary>
public class Messenger
{
    public static Messenger Defalut = new Messenger();

    //支持重复key的字典
    Dictionary<string, List<dynamic>> cache = new Dictionary<string, List<dynamic>>();
    private Messenger()
    {
    }
    public void Sub<T>(string key, Action<T> act)
    {
        if (!cache.ContainsKey(key))
            cache.Add(key, new List<dynamic>());
        cache[key].Add(act);
    }
    public void UnSub<T>(string key, Action<T> act)
    {
        if (cache.ContainsKey(key))
        {
            var items = cache[key].Skip(0).ToList();
            foreach (var item in items)
            {
                if (item is Action<T> actExist)
                {
                    cache[key].Remove(actExist);
                }
            }
        }

    }
    public void Pub<T>(string key, T data)
    {
        if (cache.TryGetValue(key, out List<dynamic> list))
        {
            foreach (var item in list)
            {
                if (item is Action<T> act)
                {
                    act?.Invoke(data);
                }
            }
        }
    }


}
