//
// Created by sebastian on 05.08.26.
//

#ifndef COLORRACE_EVENTBUS_H
#define COLORRACE_EVENTBUS_H
#include <functional>
#include <mutex>

namespace engine {
    class IEventBus {
    public:
        virtual ~IEventBus() = default;
    };

    template<typename Event>
    class EventBus {
    public:
        using Handler = std::function<void(Event&)>;

        void subscribe(Handler handler) {
            std::lock_guard<std::mutex> lock(m_mutex);
            m_handlers.push_back(handler);
        }

        void publish(Event& event) const {
            std::vector<Handler> handlersCopy;
            {
                std::lock_guard<std::mutex> lock(m_mutex);
                handlersCopy = m_handlers;
            }
            for (const auto& handler : handlersCopy) {
                handler(event);
            }
        }
    private:
        mutable std::mutex m_mutex;
        std::vector<Handler> m_handlers;
    };
} // engine

#endif //COLORRACE_EVENTBUS_H
