#include "CURLUtil.h"

int CURL_SetEncodedPostData(int nThreadIndex, CURL *pCurlContext, char *pEncodedPostData, int nPostDataOffset, int nEncodedPostDataLength, const char *pszParameterKey, const char *pszParameterData)
{
    char *pszEncodedPostValueKey;
    char *pszEncodedPostValueData;
    int nResultStringLength;

    pszEncodedPostValueKey = curl_easy_escape(pCurlContext, pszParameterKey, 0);
    if (pszEncodedPostValueKey == NULL)
    {
        WriteLog(LogType_StandardOut, LogLevel_Info, "[Thread:%02d]curl_escape error[Input:%s]!", nThreadIndex, pszParameterKey);
        return CURL_ERR_CANNOT_ADD_PARAMETER;
    }
    pszEncodedPostValueData = curl_easy_escape(pCurlContext, pszParameterData, 0);
    if (pszEncodedPostValueKey == NULL)
    {
        WriteLog(LogType_StandardOut, LogLevel_Info, "[Thread:%02d]curl_escape error[Input:%s]!", nThreadIndex, pszParameterData);
        curl_free(pszEncodedPostValueKey);
        return CURL_ERR_CANNOT_ADD_PARAMETER;
    }
    snprintf(pEncodedPostData + nPostDataOffset, nEncodedPostDataLength - nPostDataOffset, "%s=%s&", pszEncodedPostValueKey, pszEncodedPostValueData);
    nResultStringLength = strnlen(pEncodedPostData, nEncodedPostDataLength);
    curl_free(pszEncodedPostValueKey);
    curl_free(pszEncodedPostValueData);
    return nResultStringLength;
}

size_t CURL_WriteMemoryCallback(void *pData, size_t nSize, size_t nMemoryBlockSize, void *pStream)
{
    size_t nTotalSize = nSize * nMemoryBlockSize;
    struct HTML_CONTEXT_DATA *pHtmlContextData = (struct HTML_CONTEXT_DATA *)pStream;

    pHtmlContextData->pData = (char*)realloc(pHtmlContextData->pData, pHtmlContextData->nDataSize + nTotalSize + 1);
    if (pHtmlContextData->pData)
    {
            memcpy(&(pHtmlContextData->pData[pHtmlContextData->nDataSize]), pData, nTotalSize);
            pHtmlContextData->nDataSize += nTotalSize;
            pHtmlContextData->pData[pHtmlContextData->nDataSize] = '\0';
    }

    return nTotalSize;
}




