#include "event_manager.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(std::shared_ptr<ThreadPool> threadPool)
        : threadPool(threadPool)
    {
    }

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

        HandlerList *list = nullptr;

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

        for (auto fn_ptr: *list)
        {
            threadPool->submit([fn = fn_ptr.get(),name,data]
            {
                try
                {
                    (*fn)(Event(name, data));
                } catch (const std::exception &e)
                {
                    LOGGER_ERROR("事件处理异常：{} {}", name, e.what());
                }catch (...)
                {
                    LOGGER_ERROR("事件处理异常：{}", name);
                }
            });
        }
    }
} // zsy
