using System;
using System.Collections.Generic;

namespace JacekMatulewski.WpfUtils
{
    public interface IMessage { }

    public interface IMessageHandler { } //potrzebne ze względu na brak możliwości rzutowania Typ<Potomne> na Typ<Bazowe> 

    public interface IMessageHandler<Message> : IMessageHandler
        where Message : IMessage
    {
        void Handle(Message message);
    }

    public interface IMessageBus<TMessage>
        where TMessage : IMessage
    {
        void Send<Message>(Message message) where Message : TMessage;
    }

    public abstract class MessageDispatcher<TMessage> : IMessageBus<TMessage>
        where TMessage : IMessage
    {
        protected Dictionary<Type, IMessageHandler> messageHandlers = new Dictionary<Type, IMessageHandler>();

        public void AddHandler(Type messageType, IMessageHandler messageHandler)
        {
            if (!messageHandlers.ContainsKey(messageType)) messageHandlers.Add(messageType, messageHandler);
            else messageHandlers[messageType] = messageHandler;
        }

        public void RemoveHandler(Type messageType)
        {
            if (!messageHandlers.ContainsKey(messageType)) messageHandlers.Remove(messageType);
        }

        public virtual void Send<Message>(Message message)
            where Message : TMessage
        {
            IMessageHandler<Message> messageHandler = (IMessageHandler<Message>)messageHandlers[typeof(Message)];
            messageHandler.Handle(message);
        }
    }
}
