/**
 *
 *  httpHelper.cc
 *
 */

#include "httpHelper.hpp"

#include "dataTypeList.hpp"

using namespace std;
using namespace drogon;

void httpHelper::initAndStart(const Json::Value &config)
{
    /// Initialize and start the plugin
}

void httpHelper::shutdown() 
{
    /// Shutdown the plugin
}

/**
 * @description: 创建错误恢复
 * @return {*}
 */
HttpResponsePtr httpHelper::makeWrongReply(std::string data){
    HttpResultMsg<HttpNull, HttpNull> msg;
    HttpResponsePtr resp;
    msg.code = "502";
    msg.status = "Failure";
    msg.msg = data;
    msg.attr1 = "服务不可用";
    std::string json;
    msg.objectToJson(json);
    resp->setStatusCode(k502BadGateway);
    resp->setBody(json);
    return resp;
}

/**
 * @description: 回复请求
 * @param {pair<ReqResult, HttpResponsePtr>} result
 * @param {function<void (HttpResponsePtr &)>} &
 * @return {*}
 */
HttpResponsePtr httpHelper::replyRequest(std::pair<ReqResult, HttpResponsePtr> result, const HttpMethod method){
    HttpResultMsg<HttpNull, HttpNull> msg;
    HttpResponsePtr resp;
    resp = HttpResponse::newHttpResponse();
    std::string json;
    if(result.first != ReqResult::Ok){
        ErrorL << "error while sending request to server! result " << result.first << std::endl;
        msg.code = "502";
        msg.status = "Failure";
        msg.attr1 = "服务不可用";
        msg.objectToJson(json);
        resp->setBody(json);
        return resp;
    }
    resp->setStatusCode(result.second->getStatusCode());
    K8sServerResultMsy<HttpNull> rev_msg;
    if(rev_msg.jsonToObject(result.second->getBody().data()))
    {
        msg.status = rev_msg.status;
        msg.code = rev_msg.code;
        msg.msg = rev_msg.message;
    }else{
        msg.code = std::to_string(result.second->getStatusCode());
        msg.status = "Failure";
        msg.attr1 = result.second->getBody().data();
        switch (method)
        {
        case Get:
            if(result.second->getStatusCode() == k200OK) msg.status = "Success";
            break;
        case Post:
            if(result.second->getStatusCode() == k201Created) msg.status = "Success";
            break;
        case Delete:
            if(result.second->getStatusCode() == k200OK) msg.status = "Success";
            break;
        case Put:
            if(result.second->getStatusCode() == k200OK) msg.status = "Success";
            break; 
        default:
            break;
        }
    }
    msg.attr1 = result.second->getBody().data();
    msg.objectToJson(json);
    resp->setBody(json);
    return resp;
}

