//
// Created by Ht on 2022/8/27.
//

#ifndef INC_1_LIBDEVCPP_QJAGAFFICUTIL_H
#define INC_1_LIBDEVCPP_QJAGAFFICUTIL_H

#include <qlibc/qlibc.h>

namespace jedge {
    class JE_API QJAGafficUtil {

    public:

        static std::string getBaseFromSiteData(const qlibc::QData &params, const std::string& http) {
            auto host = params.getObjFmtString(http+".host");
            if(host=="localhost") host = "127.0.0.1";
            auto port = params.getObjFmtInt(http+".port");
            if(port==-1) port = http=="http"?80:443;
            auto prefix = params.getObjFmtString(http+".prefix");
            return StringUtils::formatString("%s://%s:%d%s",http.c_str(),host.c_str(),port,prefix.c_str());
        }

        static std::string getMqttData(const qlibc::QData &params, const std::string& mqtt) {
            auto host = params.getObjFmtString(mqtt+".server");
            if(host=="localhost") host = "127.0.0.1";
            auto port = params.getObjFmtInt(mqtt+".port");
            if(port==-1) port = 1883;
            auto username = params.getObjFmtString(mqtt+".username");
            if(username.size()>10) username=""; //保护非测试账号
            auto password = params.getObjFmtString(mqtt+".password");
            if(password.size()>12) password=""; //保护非测试账号
            return StringUtils::formatString("%s://%s:%d@%s:%s",mqtt.c_str(),host.c_str(),port, username.c_str(), password.c_str());
        }

        static std::string getLocalDeviceSn(jedge::ChannelOperator& opr, jedge::MgService& service) {
            qlibc::QData req,resp;
            service.postServiceRequest(opr.name(), "config/getDeviceSn", req, resp);
            return IsMsgOk(resp)?resp.getString("sn"):"";
        }

        static void getIpAddressOnPublicNet(qlibc::QData& resp) {
            string body;
            string ipResponse;
            httplib::Client ipclient("pv.sohu.com");
            auto res = ipclient.Post("/cityjson?ie=utf-8");

            if (res != nullptr) {
                body = res->body;
                std::string::size_type start, end;
                start = body.find('{');
                end = body.find('}');
                if(start != string::npos && end != string::npos){
                    ipResponse = body.substr(start, end - start + 1);
                    resp.loadFromString(ipResponse);
                }else{
                    QLog("===>can't get public network ip\n");
                }
            }else{
                QLog("===>can't get public network ip\n");
            }
        }
    };
}
#endif //INC_1_LIBDEVCPP_QJAGAFFICUTIL_H
