#include "networking.h"

int wifiConf = 1; //external variable for the selected wifi configuration
char *dat; //external data for fetched data
size_t datsz; //the size of the char *dat

int net_thread(SceSize args, void *argp)
{
	char *URL = malloc(args);
	URL = memcpy(URL, argp, args);
	//while(1){
		if(pspSdkInetInit() != 0){
			printf(MODULE_NAME ": Error, could not initialise the network %08X\n", pspSdkInetInit());
			//break;
		}
		struct wifiConf wifiList[10];
	getWifiList(&wifiList);
	printf("\n%s\n", wifiList[1].name);
		if(connect_to_apctl(wifiConf)){
			fetchData(URL);
		}
	//}
	sceKernelExitDeleteThread(0);//Jobs Done Kill this thread
	return 0;
}

int loadInet(){
	if(pspSdkLoadInetModules() < 0)
	{
		printf("Error, could not load inet modules\n");
		sceKernelSleepThread();
	}
	else printf("\nInet modules loaded\n");
	return 1;
}

int fetchFromUrl(char *url, int confNum){

	wifiConf = confNum;
	/* Create a user thread to do the real work */
	SceUID thid = sceKernelCreateThread("net_thread", net_thread, 0x18, 0x10000, PSP_THREAD_ATTR_USER, NULL);
	printf("net_thread created\n");
	
	if(thid >= 0)
	{
		sceKernelStartThread(thid, strlen(url), url);
	}
	return 1;
}

size_t WriteMemoryCallback(void *ptr, size_t size, size_t nmemb, void *data)
{
  	datsz = size * nmemb;
  	dat = malloc(datsz);
 	dat = (char *)ptr;
 	data = malloc(datsz);
 	data = (char *)ptr;
  return size * nmemb;
}
  
char *fetchData(char *URL)
{
  char *junk;
  CURL *curl_handle;
  curl_global_init(CURL_GLOBAL_ALL);
  curl_handle = curl_easy_init();
  curl_easy_setopt(curl_handle, CURLOPT_URL, URL);
  curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, WriteMemoryCallback);
  curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA,(void *)junk);
  curl_easy_setopt(curl_handle, CURLOPT_USERAGENT, "libcurl-agent/1.0");
  curl_easy_perform(curl_handle);
  curl_easy_cleanup(curl_handle);
  
  return dat;
}


/*char getWifiName(int conf){
	netData name;
	sceUtilityGetNetParam(conf, PSP_NETPARAM_NAME, &name);
	char *netname = name.asString;
	return netname;
}
*/

int getWifiList(struct wifiConf *confList){
	int i;
	for(i = 0; sceUtilityCheckNetParam(i) == 0; i ++){
		netData name;
		sceUtilityGetNetParam(i, PSP_NETPARAM_NAME, &name);
		confList[i].name = name.asString;
		confList[i].num = i;
	}
	return 1;
}

/*char getScores(){
	char dat;
	fetchData("?com=scoreList", &dat);
	return dat;
}

char putScore(char *name, char *level, char *score){
	char *args;
	sprintf(args, "?com=scorePut&name=%s&level=%s&score=%s",name,level,score);
	char dat;
	fetchData(args, &dat);
	return dat;
}

char getMapList(){
	char dat;
	fetchData("?com=mapList", &dat);
	return dat;
}

char getMap(char *name, char *savePath){
	char dat = fetchData(strcat("?com=mapGe&name=t",name), &dat);
	FILE *file = fopen(savePath,"r+");
	fwrite(dat, sizeof(char), 100000, file);
	fclose(file);
	return '1';
}

char putMap(char *name, char *creator, char *data, char *rating){
	char *args;
	sprintf(args, "?com=mapPut&name=%s&creator=%s&data=%s&rating=%s", name, creator, data, rating);
	char dat = fetchData(args);
	return dat;
}
*/
/* Connect to an access point */
int connect_to_apctl(int config)
{
	int err;
	int stateLast = -1;
	/* Connect using the first profile */
	err = sceNetApctlConnect(config);
	if (err != 0)
	{
		printf(MODULE_NAME ": sceNetApctlConnect returns %08X\n", err);
		return 0;
	}
	printf(MODULE_NAME ": Connecting...\n");
	while (1)
	{
		int state;
		err = sceNetApctlGetState(&state);
		if (err != 0)
		{
			printf(MODULE_NAME ": sceNetApctlGetState returns $%x\n", err);
			break;
		}
		if (state > stateLast)
		{
			printf("  connection state %d of 4\n", state);
			stateLast = state;
		}
		if (state == 4)
			break;  // connected with static IP
		// wait a little before polling again
		sceKernelDelayThread(50*1000); // 50ms
	}
	printf(MODULE_NAME ": Connected!\n");
	if(err != 0)
	{
		return 0;
	}
	return 1;
}
