#include "event_manager.h"

#include "logging.h"

namespace zsy
{
    EventManager::Event::Event(std::string name, const std::string &data)
        : name(std::move(name))
    {
        if (data.empty())
        {
            this->data = std::nullopt;
        } else
        {
            this->data = nlohmann::json::parse(data);
        }
    }

    EventManager::EventManager()
    {
    }

    void EventManager::subscribe(const std::string &name, const EventHandler &handler)
    {
        std::lock_guard lock(handlersMutex);
        auto handlerPtr = std::make_shared<EventHandler>(handler);
        handlers[name].push_back(handlerPtr);
    }

    void EventManager::publish(const std::string &name, const std::string &data) noexcept
    {
        LOGGER_INFO("发布事件：{} {}", name, data);

        HandlerList *list = nullptr;

        {
            std::shared_lock lock(handlersMutex);
            auto it = handlers.find(name);
            if (it != handlers.end())
            {
                list = &it->second;
            } else
            {
                LOGGER_WARN("无处理器，事件：{}", name);
                return;
            }
        }

        if (list == nullptr || list->empty())
        {
            return;
        }
        for (const auto &fn_ptr: *list)
        {
            try
            {
                (*fn_ptr.get())(Event(name, data));
            } catch (const std::exception &e)
            {
                LOGGER_ERROR("事件处理异常：{} {}", name, e.what());
            } catch (...)
            {
                LOGGER_ERROR("事件处理异常：{}", name);
            }
        }
    }
} // zsy
