#ifndef HTTP_SVR_H
#define HTTP_SVR_H
#include <httplib.h>
#include <shared_mutex>

#include "httpsvr_properties.h"

namespace zsy
{
    struct HttpSvrConfig
    {
        HttpSvrProperties httpSvr;
    };

    inline void from_json(const nlohmann::json &j, HttpSvrConfig &o)
    {
        PARSE_JSON(httpSvr, o.httpSvr);
    }

    class HttpSvr
    {
        HttpSvrProperties config;
        // 0-->不可用、1-->可用
        uint8_t status;
        std::shared_mutex status_mtx;
        std::unique_ptr<std::thread> svrThread;

    public:
        std::unique_ptr<httplib::Server> svr;
        explicit HttpSvr(const nlohmann::json &config);

        template<typename Func>
        requires std::invocable<Func, const httplib::Request&, httplib::Response&>
        void postEndpoint(std::string path, Func &&handler)
        {
            std::shared_lock lock(status_mtx);
            if (status == 0)
            {
                LOGGER_ERROR("HTTP 服务不可用");
                return;
            }
            svr->Post(std::move(path), std::forward<Func>(handler));
        }

        template<typename Func>
        void getEndpoint(std::string path, Func &&handler)
        {
            std::shared_lock lock(status_mtx);
            if (status == 0)
            {
                LOGGER_ERROR("HTTP 服务不可用");
                return;
            }
            svr->Get(path, std::forward<Func>(handler));
        }

        ~HttpSvr();
    };
} // zsy

#endif //HTTP_SVR_H
