#include "http_svr.h"

#include <boost/asio/config.hpp>

#include "app/app.h"
#include "common/spdlog/logging.h"
#include "common/utils/thread_pool.h"

namespace zsy
{
    HttpSvr::HttpSvr(const HTTPConfig_Svr &config)
        : config(config), svr(std::make_shared<httplib::Server>())
    {
        try
        {
            reportInitializing();
            LOGGER_INFO("启动 HTTP 服务器，端口：{}", this->config.port());
            svrThread = std::make_unique<std::jthread>([this]
            {
                ThreadPool::submit([this]
                {
                    std::this_thread::sleep_for(std::chrono::seconds(1));
                    LOGGER_INFO("HTTP 服务器已启动，端口：{}", this->config.port());
                    reportAvailable();
                });
                if (!this->svr->listen("0.0.0.0", this->config.port()))
                {
                    reportTerminated();
                    LOGGER_ERROR("服务器启动失败，端口：{}", this->config.port());
                    return;
                }
                reportTerminated();
                LOGGER_INFO("HTTP 服务器已停止");
            });
        } catch (const std::exception &e)
        {
            reportTerminated();
            LOGGER_ERROR("HTTP 服务器启动失败：", e.what());
            svrThread.reset();
        } catch (...)
        {
            reportTerminated();
            LOGGER_ERROR("未知异常 HTTP 服务器启动失败");
            svrThread.reset();
        }
        waitStarted();
    }

    std::string HttpSvr::name() const noexcept
    {
        return config.name();
    }

    std::string HttpSvr::sn() const noexcept
    {
        return config.sn();
    }

    void HttpSvr::init()
    {
        if (!App::APP_CONFIG->has_http_config())return;
        if (!App::APP_CONFIG->http_config().has_svr())return;
        HTTP_SVR = std::make_shared < HttpSvr > (App::APP_CONFIG->http_config().svr());
    }

    void HttpSvr::destroy()
    {
        HTTP_SVR.reset();
        HTTP_SVR = nullptr;
    }

    std::shared_ptr<HttpSvr> HttpSvr::get()
    {
        return HTTP_SVR;
    }

    HttpSvr::~HttpSvr()
    {
        reportTerminated();
        LOGGER_INFO("正在停止 HTTP 服务器");
        if (svr)
        {
            svr->stop();
        }
    }
} // zsy