using System;
using System.Collections.Generic;

public class EventBus
{
    private static Dictionary<Type, Delegate> s_event = new();
    
    public static void Subscribe<T>(Action<T> listener)
    {
        Type eventType = typeof(T);
        if (s_event.TryGetValue(eventType, out var exisitingDelegate))
        {
            s_event[eventType] = Delegate.Combine(exisitingDelegate, listener);
        }
        else
        {
            s_event[eventType] = listener;
        }
    }
    
    public static void Unsubscribe<T>(Action<T> listener)
    {
        Type eventType = typeof(T);
        if (s_event.TryGetValue(eventType, out var existingDelegate))
        {
            var newDelegate = Delegate.Remove(existingDelegate, listener);
            if (newDelegate == null)
            {
                s_event.Remove(eventType);
            }
            else
            {
                s_event[eventType] = newDelegate;
            }
        }
    }
    
    public static void Raise<T>(T eventArgs)
    {
        if (s_event.TryGetValue(typeof(T), out var exisingDelegate))
        {
            (exisingDelegate as Action<T>)?.Invoke(eventArgs);
        }
    }
    
}
