/***************************************************************************
*                                  _   _ ____  _
*  Project                     ___| | | |  _ \| |
*                             / __| | | | |_) | |
*                            | (__| |_| |  _ <| |___
*                             \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2011, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at http://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
/* This is an example application source code using the multi interface. */

#include <stdio.h>
#include <conio.h>
#include <string.h>

#include <WinSock2.h>
#include <windows.h>

/* curl stuff */
#include <curl/curl.h>
// #include <curl/multi.h>
// 
// #ifdef  __cplusplus
//extern "C" {
//#endif
// #include <multiif.h>
// #ifdef  __cplusplus
//}
//#endif

/*
* Download a HTTP file and upload an FTP file simultaneously.
*/

#define HANDLECOUNT 3
const char* urls[HANDLECOUNT] = 
{
 	"http://www.sohu.com"
	,"http://www.sina.com.cn"
	,"http://www.qq.com"
};

int cyc[HANDLECOUNT] =
{
	0
	,0
	,0
};

size_t write_callback(char *buffer,
					  size_t size,
					  size_t nitems,
					  void *outstream)
{
	return size * nitems;
}

int main(int argc, char** argv)
{
	CURL *handles[HANDLECOUNT];
	CURLM *multi_handle;

	int cycmax = 10;
	if(argc > 1) cycmax = atoi(argv[1]);
	if(cycmax < 1) cycmax = 10;

	int still_running; /* keep number of running handles */
	int still_exist;
	int i;

	CURLMsg *msg; /* for picking up messages with the transfer status */
	int msgs_left; /* how many messages are left */

	CURLcode retcode = curl_global_init(CURL_GLOBAL_ALL);
	if(retcode != CURLE_OK)
	{
		printf("Curl init error!\n");
		return -1;
	}

	/* init a multi stack */
	multi_handle = curl_multi_init();
	curl_multi_setopt(multi_handle, CURLMOPT_MAXCONNECTS, 3);

	/* Allocate one CURL handle per transfer */
	for (i=0; i<HANDLECOUNT; i++)
	{
		handles[i] = curl_easy_init();
		curl_easy_setopt(handles[i], CURLOPT_URL, urls[i]);
		if(argc > 2) curl_easy_setopt(handles[i], CURLOPT_VERBOSE, 1);
		else curl_easy_setopt(handles[i], CURLOPT_VERBOSE, 0);
		curl_easy_setopt(handles[i], CURLOPT_WRITEFUNCTION, write_callback);
		curl_multi_add_handle(multi_handle, handles[i]);
	}

	/* we start some action by calling perform right away */
	curl_multi_perform(multi_handle, &still_running);

	while(still_exist)
	{
		struct timeval timeout;
		int rc; /* select() return code */

		fd_set fdread;
		fd_set fdwrite;
		fd_set fdexcep;
		int maxfd = -1;

		long curl_timeo = -1;

		FD_ZERO(&fdread);
		FD_ZERO(&fdwrite);
		FD_ZERO(&fdexcep);

		/* set a suitable timeout to play around with */
		timeout.tv_sec = 1;
		timeout.tv_usec = 0;

		curl_multi_timeout(multi_handle, &curl_timeo);
		if(curl_timeo >= 0) {
			timeout.tv_sec = curl_timeo / 1000;
			if(timeout.tv_sec > 1)
				timeout.tv_sec = 1;
			else
				timeout.tv_usec = (curl_timeo % 1000) * 1000;
		}

		/* get file descriptors from the transfers */
		CURLMcode mrc = curl_multi_fdset(multi_handle, &fdread, &fdwrite, &fdexcep, &maxfd);
		if(mrc != CURLM_OK)
		{
			fprintf(stdout, "curl_multi_fdset error: %s\n", curl_multi_strerror(mrc));
			goto END;
		}

		/* In a real-world program you OF COURSE check the return code of the
		function calls.  On success, the value of maxfd is guaranteed to be
		greater or equal than -1.  We call select(maxfd + 1, ...), specially in
		case of (maxfd == -1), we call select(0, ...), which is basically equal
		to sleep. */

		rc = select(maxfd+1, &fdread, &fdwrite, &fdexcep, &timeout);

		switch(rc)
		{
		case SOCKET_ERROR :
			/* select error */
			printf("Select error: %d\n", WSAGetLastError());
			goto END;
		case 0: /* timeout */
			curl_multi_perform(multi_handle, &still_running);
			continue;
		default: /* action */
			break;
		}

		/* See how the transfers went */
		while ((msg = curl_multi_info_read(multi_handle, &msgs_left)))
		{
			int idx, found = 0;

			/* Find out which handle this message is about */
			for (idx=0; idx<HANDLECOUNT; idx++) {
				found = (msg->easy_handle == handles[idx]);
				if(found)
					break;
			}

			if(found)
			{
				if(msg->data.result == CURLE_OK)
				{					
					fprintf(stderr, "%d-%d: Fetch %s ok, handle 0x%x\n", idx, cyc[idx], urls[idx], handles[idx]);
				}
				else
				{
					fprintf(stderr, "%d-%d: Fetch %s fail, handle 0x%x, error: 0x%x\n", idx, cyc[idx], urls[idx], handles[idx], msg->data.result);
				}

				cyc[idx]++;
				curl_multi_remove_handle(multi_handle, handles[idx]);
				if(cyc[idx] < cycmax)
				{
					//curl_easy_setopt(handles[idx], CURLOPT_URL, urls[idx]);
					curl_multi_add_handle(multi_handle, handles[idx]);
				}
				else
				{
					fprintf(stderr, "%d-%d: Fetch %s end, handle 0x%x\n", idx, cyc[idx], urls[idx], handles[idx]);
				}
			}
		}

		curl_multi_perform(multi_handle, &still_running);
		//printf("Still runing %d\n", still_running);

		if(_kbhit())
			break;
	}

	while ((msg = curl_multi_info_read(multi_handle, &msgs_left)))
	{
		int idx, found = 0;

		/* Find out which handle this message is about */
		for (idx=0; idx<HANDLECOUNT; idx++) {
			found = (msg->easy_handle == handles[idx]);
			if(found)
				break;
		}

		if(found)
		{
			if(msg->data.result == CURLE_OK)
			{
				fprintf(stderr, "%d-%d: Fetch %s ok after break\n", idx, cyc[idx],  urls[idx]);
				curl_multi_remove_handle(multi_handle, handles[idx]);
			}
			else
			{
				fprintf(stderr, "%d: Fetch %s fail after break, error: %d\n", cyc[idx],  urls[idx], msg->data.result);
				curl_multi_remove_handle(multi_handle, handles[idx]);
			}
		}
	}

END:
	curl_multi_cleanup(multi_handle);

	/* Free the CURL handles */
	for (i=0; i<HANDLECOUNT; i++)
		curl_easy_cleanup(handles[i]);

	curl_global_cleanup();

	return 0;
}