#include <stdio.h>
#include <curl/curl.h>
#include <curl/easy.h>
#include <curl/multi.h>
#include <curl/types.h>


static size_t writeCallback(void* ptr, size_t size, size_t nmemb, void* data)
{
    CURL* handle= (CURL*) data;
    size_t totalSize = size * nmemb;

    long httpCode = 0;
    CURLcode err = curl_easy_getinfo(handle, CURLINFO_RESPONSE_CODE, &httpCode);
    printf("writeCallback::HttpCode:-- %d --\n", httpCode);

    return totalSize;
}

static size_t headerCallback(char* ptr, size_t size, size_t nmemb, void* data)
{
    CURL* handle= (CURL*) data;
    size_t totalSize = size * nmemb;

    long httpCode = 0;
    CURLcode err = curl_easy_getinfo(handle, CURLINFO_RESPONSE_CODE, &httpCode);
    printf("writeCallback::HttpCode:-- %d --\n", httpCode);
    if(401 == httpCode){
        curl_easy_setopt(handle, CURLOPT_USERPWD, "WrongUser:WrongPassword ");
        curl_easy_setopt(handle, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
    }


    return totalSize;
}

CURLM* m_curlMultiHandle;

int main()
{
    CURL* handle = curl_easy_init();
    curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, writeCallback);
    curl_easy_setopt(handle, CURLOPT_WRITEDATA, handle);
    curl_easy_setopt(handle, CURLOPT_HEADERFUNCTION, headerCallback);
    curl_easy_setopt(handle, CURLOPT_WRITEHEADER, handle);
    curl_easy_setopt(handle, CURLOPT_AUTOREFERER, 1);
    curl_easy_setopt(handle, CURLOPT_FOLLOWLOCATION, 1);
    curl_easy_setopt(handle, CURLOPT_MAXREDIRS, 10);
    curl_easy_setopt(handle, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
    curl_easy_setopt(handle, CURLOPT_USERPWD, " ");
    curl_easy_setopt(handle, CURLOPT_HTTPGET, 1);

    CURLMcode ret = curl_multi_add_handle(m_curlMultiHandle, handle);
    if (ret && ret != CURLM_CALL_MULTI_PERFORM)
        printf("Add handle failed\n");

    int runningHandles = 0;
    while (curl_multi_perform(m_curlMultiHandle, &runningHandles) == CURLM_CALL_MULTI_PERFORM) { }
    while (1) {
        int messagesInQueue;
        CURLMsg* msg = curl_multi_info_read(m_curlMultiHandle, &messagesInQueue);
        if (!msg)
            break;

        // find the node which has same d->m_handle as completed transfer
        CURL* newHandle = msg->easy_handle;
        ASSERT(newHandle);
        if (CURLMSG_DONE == msg->msg){
            printf("CURL returned DONE\n");
            curl_multi_remove_handle(m_curlMultiHandle, handle);
            break;
        }
    }
    return 0;
}




