#include "CLogTrack.h"

#include "json/json.h"

std::shared_ptr<CLogTrack> g_logPtr = nullptr;

CLogData::CLogData()
{

}

CLogData::~CLogData()
{
    m_LogList.clear();
}

QString CLogData::genLogJson()
{
    Json::Value jLog;
    jLog[LOG_CONSTANT_DEF::SOURCE] = LOG_CONSTANT_DEF::WIN;
    Json::Value item;
    for_each(m_LogList.begin(), m_LogList.end(), [&](CLogInfo v){
        item[v.sKey.toStdString()] = v.sValue.toStdString();
    });
    jLog[LOG_CONSTANT_DEF::LOGS].append(item);
    return  Json::FastWriter().write(jLog).c_str();
}

void CLogData::pushLog(QString sKey, QString sValue)
{
    CLogInfo li;
    li.sKey = sKey;
    li.sValue = sValue;
    m_LogList.push_back(li);
}

CLogTrack::CLogTrack(QString sProjectName, QString sEndpoint, QString sLogstore)
{
    m_sUrl = QString("https://%1.%2/logstores/%3/track").arg(sProjectName).arg(sEndpoint).arg(sLogstore);
    m_bIsRun = true;
    m_thread = std::thread(std::bind(&CLogTrack::threadProc, this));
}

CLogTrack::~CLogTrack()
{
    std::scoped_lock lock(m_logMutex);
    m_LogList.clear();
    m_bIsRun = false;
    m_thread.join();
}

void CLogTrack::putLog(CLogData log)
{
    std::scoped_lock lock(m_logMutex);
    m_LogList.push_back(log);
}

void CLogTrack::threadProc()
{
    while(m_bIsRun)
    {
        if(m_LogList.size() > 0)
        {
            CLogData ld;
            {
                std::scoped_lock lock(m_logMutex);
                ld = m_LogList.front();
                m_LogList.pop_front();
            }

            int nCode = 0;
            std::string sResponseStr = "";
            QString sBody = ld.genLogJson();
            m_httpClient.addHeader(LOG_CONSTANT_DEF::X_LOG_APIVERSION, LOG_CONSTANT_DEF::LOG_API_VERSION);
            m_httpClient.addHeader(LOG_CONSTANT_DEF::X_LOG_BODYRAWSIZE, std::to_string(sBody.length()));
            if(m_httpClient.post(m_sUrl.toStdString(), sBody.toStdString(), sResponseStr, nCode))
            {
                if(nCode == 200)//成功
                {
//                    OC oc;
//                    emit logFaild(oc);
                }
            }
            else
            {
                //失败
            }
        }
        else
        {
            Sleep(100);
        }
    }
}

