//
// Created by sebastian on 06.08.26.
//

#ifndef COLORRACE_EVENTCHANNELS_H
#define COLORRACE_EVENTCHANNELS_H
#include <memory>
#include <typeindex>

#include "EventBus.h"


namespace engine {
    class EventChannels {
    public:
        template<typename Event>
        void subscribe(typename EventBus<Event>::Handler handler) {
            getBus<Event>().subscribe(std::move(handler));
        }

        template<typename Event>
        void publish(Event& event) {
            getBus<Event>().publish(event);
        }

        template<typename Event>
        EventBus<Event>& getBus() {
            auto key = std::type_index(typeid(Event));
            auto it = m_buses.find(key);
            if (it == m_buses.end()) {
                auto bus = std::make_unique<EventBus<Event>>();
                auto* ptr = bus.get();
                m_buses.emplace(key, std::move(bus));
                return *ptr;
            }
            return static_cast<EventBus<Event>&>(*it->second);
        }
    private:
        std::unordered_map<std::type_index, std::unique_ptr<IEventBus>> m_buses;
    };
}

#endif //COLORRACE_EVENTCHANNELS_H
