#include <pspsdk.h>
#include <stdlib.h>
#include <string.h>
#include <pspthreadman.h>
#include <stdio.h>
#include <pspnet.h>
#include <pspwlan.h>
#include <pspnet_adhoc.h>
#include <pspnet_adhocctl.h>
#include "std.h"


char BROADCAST_MAC[6];

int pdpID = -1;

bool pdpInit = false;

int recvPDP(void *buffer, unsigned int *length)
{
	int port = 0;
	char mac[20];
	int pdpStatLength=20;
	pdpStatStruct pspStat;

	sceNetAdhocGetPdpStat(&pdpStatLength, &pspStat);

	if(pspStat.rcvdData < 1)
	{
		sceNetAdhocPdpRecv(pdpID,mac,&port,buffer,length,0,0);
		return 1;
	}
	else
		return 0;
}

int sendPDP(void *buffer, int length)
{
	sceNetAdhocPdpSend(pdpID,
			&BROADCAST_MAC[0],
			0x309,
			buffer,
			length,
			0,	// 0 in lumines
			0);	// 1 in lumines

	return 0;
}


void sendMSG(char *MSG)
{
	sendPDP(&MSG, sizeof(MSG));
}

void recvMSG(char *MSG)
{
	int recvLEN;

	recvPDP(&MSG, &recvLEN);
}


void initAll()
{
	struct productStruct product;

	//Set the product information to connect to the CTL
	strcpy(product.product, "ULUS99999");
	product.unknown = 0;

	//Init the net module for WLAN
	sceNetInit(0x20000, 0x20, 0x1000, 0x20, 0x1000);



	//Init the adhoc libraries
	sceNetAdhocInit();

	//Init the adhoc ctl libraries
	sceNetAdhocctlInit(0x2000, 0x20, &product);


}
void termAll()
{
	sceNetAdhocctlTerm();
	sceNetAdhocTerm();
	sceNetTerm();
}
void connectAdhoc()
{
	char mac[6];
	int err;

	//Connect to adhoc ctl
	sceNetAdhocctlConnect("");

	//This is from BlackPhoenix's Adhoc Example
	int stateLast = -1;
	while (1)
	{
		int state;
		err = sceNetAdhocctlGetState(&state);
		if (state > stateLast)
			stateLast = state;
		if (state == 1)
			break;  // connected
		// wait a little before polling again
		sceKernelDelayThread(50*1000); // 50ms
	}
	
	//Get the MAC address
	sceWlanGetEtherAddr(mac);

	//Create a PDP
	pdpID = sceNetAdhocPdpCreate(mac, 0x309, 0x400, 0);

	if(pdpID >= 0)
		pdpInit = true;

	int i;
	for(i=0;i<7;i++)
		BROADCAST_MAC[i] = 0xFF;

}
void getmac(void *themac)
{
	unsigned char sVal[7];
	memset(sVal, 0, 7);
	sceWlanGetEtherAddr(sVal); 
	sprintf(themac,"%02X:%02X:%02X:%02X:%02X:%02X", sVal[0], sVal[1], sVal[2], sVal[3], sVal[4], sVal[5]);
	
}
/*


I believe that our ad-hoc system is working well for right now.. the way to do this better would probably be with
Adhoc Matching... I think we should save this for a later release though because it's not needed right now and it
just adds more to our plate.


void creatadhoc(void *name)
{
	
	char macad[6];

	//Get the MAC address
	sceWlanGetEtherAddr(macad);
	//Connect to adhoc ctl
	sceNetAdhocctlCreateEnterGameMode(name, 1, 16, macad, 1000000, 0);
		

}
*/
