#include "http_svr.h"

#include <boost/asio/config.hpp>

namespace zsy
{
    HttpSvr::HttpSvr(const nlohmann::json &config)
        : status(0),
          config(config.get<HttpSvrConfig>().httpSvr),
          svr(std::make_unique<httplib::Server>()),
          svrThread(nullptr)
    {
        try
        {
            {
                std::unique_lock lock(status_mtx);
                status = 1;
            }
            uint16_t port = this->config.port;
            LOGGER_INFO("启动 HTTP 服务器，端口：{}", port);
            svrThread = std::make_unique<std::thread>([svr = svr.get(), port,this]() mutable
            {
                if (!svr->listen("0.0.0.0", port))
                {
                    {
                        std::unique_lock lock(status_mtx);
                        status = 0;
                    }
                    LOGGER_ERROR("服务器启动失败，端口：{}", port);
                    return;
                }
                {
                    std::unique_lock lock(status_mtx);
                    status = 0;
                }
                LOGGER_INFO("HTTP 服务器已停止");
            });
        } catch (const std::exception &e)
        {
            LOGGER_ERROR("HTTP 服务器启动失败：", e.what());
            svrThread.reset();
            std::unique_lock lock(status_mtx);
            status = 0;
        }catch (...)
        {
            LOGGER_ERROR("未知异常 HTTP 服务器启动失败");
            svrThread.reset();
            std::unique_lock lock(status_mtx);
            status = 0;
        }
    }

    HttpSvr::~HttpSvr()
    {
        {
            std::unique_lock lock(status_mtx);
            status = 1;
        }
        if (svr)
        {
            LOGGER_INFO("正在停止 HTTP 服务器");

            svr->stop();
        }
        if (svrThread && svrThread->joinable())
        {
            svrThread->join();
        }
    }
} // zsy
