#include "ApiEngine.h"

using namespace ai_matrix;

ApiEngine::ApiEngine() {}

ApiEngine::~ApiEngine() {}

APP_ERROR ApiEngine::Init()
{
    strPort0_ = engineName_ + "_" + std::to_string(engineId_) + "_0";
    strPort1_ = engineName_ + "_" + std::to_string(engineId_) + "_1";

    LogInfo << "engineId_:" << engineId_ << " ApiEngine Init ok";
    return APP_ERR_OK;
}

APP_ERROR ApiEngine::DeInit()
{
    LogInfo << "ApiEngine engineId_:" << engineId_ << " DeInit ok";
    return APP_ERR_OK;
}

APP_ERROR ApiEngine::Process()
{
    int iRet = APP_ERR_OK;

    httplib::Server svr;

    svr.Get("/hello", [](const httplib::Request& req, httplib::Response& res){
        res.set_content("Hello, World!", "text/plain");
    });



    svr.Post("/queryDataSource", [=](const httplib::Request& req, httplib::Response& res){
        std::string add_result = queryDataSource(req.body);
        Json::Value response;
        if (add_result.empty())
        {
            response["success"] = true;
            response["msg"] = add_result;
        }
        else
        {
            response["success"] = false;
            response["msg"] = add_result;
        }
        res.set_content(response.toStyledString(), "application/json");
    });

    LogInfo << "开启Api服务，端口:" << 8080;
    svr.listen("0.0.0.0", 8080);
    return APP_ERR_OK;
}

/**
 * 查看当前使用的数据源
 * @param req
 * @return
 */
std::string ApiEngine::queryDataSource(const std::string &req)
{
    try {
        Json::CharReaderBuilder readerBuilder;
        std::istringstream iss(req);
        Json::Value root;
        std::string errs;
        bool parsingSuccessful = Json::parseFromStream(readerBuilder, iss, &root, &errs);
        if (parsingSuccessful)
        {
//            std::shared_ptr<VTrainInfo> pTrainInfo = std::make_shared<VTrainInfo>();
//            pTrainInfo->strTrackNo = root["strTrackNo"].asString();
//            if (root.isMember("numCoordinate"))
            MyYaml::GetIns()->GetUseDataSourceConfig();



            // 转发到上传接口引擎中
//            outputQueMap_[strPort0_]->push(std::static_pointer_cast<void>(pTrainInfo));
            // 存储到本地数据库
//            outputQueMap_[strPort1_]->push(std::static_pointer_cast<void>(pTrainInfo));

        }
        else
        {
            return "接口调用参数异常，所传数据非json：" + req;
        }

        return "";
    }
    catch (std::exception &e)
    {
        return "接口调用失败！请求内容:" + req + "。 \n异常内容:" + std::string(e.what());
    }

}