/*
 * @Description: apiserver
 * @Version: 1.0
 * @Autor: lishengyin
 * @Date: 2022-04-01 15:44:17
 * @LastEditors: lishengyin
 * @LastEditTime: 2022-04-18 15:45:41
 */
#include "ApiServer.hpp"

namespace ins{

    std::shared_ptr<ApiServer> m_ApiServer = nullptr;

    /**
     * @description: 创建实例
     * @param {*}
     * @return {*}
     */    
    std::shared_ptr<ApiServer> ApiServer::CreateNew(int port){
        if(m_ApiServer == nullptr) m_ApiServer = std::shared_ptr<ApiServer>(new ApiServer(port));
        return m_ApiServer;
    }
    
    /**
     * @description: 创建ptr
     * @param {*}
     * @return {*}
     */    
    std::shared_ptr<ApiServer> ApiServer::getPtr(){
        return m_ApiServer;
    }

    /**
     * @description: 初始化
     * @param {*}
     * @return {*}
     */    
    int8_t ApiServer::Init() {
        if(this->valid) return OK;
        if(m_HttpService == nullptr) m_HttpService = std::make_shared<hv::HttpService>();
        if(m_HttpService == nullptr) return ERR;
        this->valid = true;
        return OK;
    }

    /**
     * @description: 释放资源
     * @param {*}
     * @return {*}
     */    
    void ApiServer::Destroy(){
        http_server_stop(&this->server_);
    }

    /**
     * @description: run
     * @param {*}
     * @return {*}
     */    
    int8_t ApiServer::Run(){
        if(this->port_ <= 0 && this->valid == false) return ERR;
        // 注册API
        if(this->RegisterApi() == ERR) return ERR;
        server_.service = this->m_HttpService.get();
        server_.port = this->port_;
        http_server_run(&server_, 0);
        return OK;
    }

    /**
     * @description: 注册API
     * @param {*}
     * @return {*}
     */    
    int8_t ApiServer::RegisterApi(){
        if(this->m_HttpService == nullptr) return ERR;
        
        // login  
        // TODO
        this->m_HttpService->GET("/LOGIN", [](HttpRequest* req, HttpResponse* resp){
            return resp->String("pong");
        });

        
        return OK;
    }
    
};