using System;
using System.Reflection;

namespace Raycast.Win32
{
    public static class MessageCenter
    {
        public static event EventHandler EnemyDead;
        public static event EventHandler RestartCommand;
        public static event EventHandler PlayerShoot;
        public static event EventHandler<int> PlayerHurt;

        public static void TriggerEnemyDead(object sender = null, EventArgs e = null) => EnemyDead?.Invoke(sender, e);
        public static void TriggerRestartCommand(object sender = null, EventArgs e = null) => RestartCommand?.Invoke(sender, e);
        public static void TriggerPlayerShoot(object sender = null, EventArgs e = null) => PlayerShoot?.Invoke(sender, e);
        public static void TriggerPlayerHurt(object sender = null, int damage = 0) => PlayerHurt?.Invoke(sender, damage);

        public static void Reset()
        {
            var type = typeof(MessageCenter);
            var events = type.GetEvents();
            foreach (var @event in events)
            {
                var eventDelegate = (MulticastDelegate)type
                    .GetField(@event.Name, BindingFlags.Static | BindingFlags.NonPublic)
                    .GetValue(null);
                if (eventDelegate != null)
                {
                    var invocations = eventDelegate.GetInvocationList();
                    foreach (var invocation in invocations)
                    {
                        @event.RemoveEventHandler(null, invocation);
                    }
                }
            }
        }
    }
}
