#include "precomp.h"
#include "SoccerClient.h"

/* Windows version of soccer client		*/
/* updated 8/8/03						*/
/* Dan Maynes-Aminzade <monzy@mit.edu>	*/

CComModule _Module;
char SERVER_IP[100];

LRESULT CSoccerClient::OnPaint( UINT, WPARAM, LPARAM, BOOL& )
{
	PAINTSTRUCT ps;
	HDC hdc = BeginPaint(&ps);
	RECT textrect = {0,0,300,100};
	TextOut(hdc,10,0,L"Sample Client",14);
	TextOut(hdc,10,40,L"Click in window and use these keys:",36);
	TextOut(hdc,10,80,L"1-5: select player",19);
	TextOut(hdc,10,120,L"up,down,left,right: change velocity",36);
	TextOut(hdc,10,160,L"spacebar: kick",15);
	EndPaint(&ps);
	return 0;
}

LRESULT CSoccerClient::OnChar( UINT, WPARAM wParam, LPARAM, BOOL& )
{
	if ((wParam>=0x31)&&(wParam<0x36)) {
		currentplayer = wParam-0x31;
	}
	return 0;
}

LRESULT CSoccerClient::OnKeydown( UINT, WPARAM wParam, LPARAM, BOOL& )
{
	SoccerPlayer *team = (CURRENT_TEAM?field.team1:field.team0);
	switch(wParam) {
		case VK_UP:
			team[currentplayer].velocity.Y -= 1.00;
			break;
		case VK_DOWN:
			team[currentplayer].velocity.Y += 1.00;
			break;
		case VK_LEFT:
			team[currentplayer].velocity.X -= 1.00;
			break;
		case VK_RIGHT:
			team[currentplayer].velocity.X += 1.00;
			break;
		case VK_SPACE:
			team[currentplayer].kick = 3.0;
			break;
	}
	return 0;
}

LRESULT CSoccerClient::OnDestroy( UINT, WPARAM, LPARAM, BOOL& )
{
	PostQuitMessage( 0 );
	return 0;
}

LRESULT CSoccerClient::OnCreate(UINT, WPARAM, LPARAM, BOOL& )
{
	server = new UDPServer(m_hWnd);
	client = new UDPClient(SERVER_IP);
	SetTimer(1,50);
	currentplayer = 0;
	return 0;
}

LRESULT CSoccerClient::OnSocketRead(UINT, WPARAM, LPARAM, BOOL& )
{
	DATAGRAM d;
	server->ReceiveData((char*)&d);
	field.ReadDatagram(&d);
	return 0;
}

LRESULT CSoccerClient::OnTimer(UINT, WPARAM, LPARAM, BOOL& )
{
	DATAGRAM d;
	ZeroMemory(&d,sizeof(DATAGRAM));
	field.FillDatagram(&d);
	client->TransmitData((char*)&d);
	return 0;
}

INT WINAPI WinMain(HINSTANCE hInstance, HINSTANCE, PSTR lpCmdLine, INT iCmdShow)
{
	_Module.Init( NULL, hInstance );

	MSG msg;
	if (strlen(lpCmdLine) > 0) {
		strcpy(SERVER_IP,lpCmdLine);
	}
	else {
		MessageBox(NULL,L"Usage: SoccerClient.exe [Server IP Address]",L"Must Specify Server IP",0);
		return FALSE;
	}

	CSoccerClient wnd;
	RECT windowrect = {0,0,WindowX,WindowY};
	wnd.Create(NULL, windowrect,_T("Sample SoccerClient"));

	while( GetMessage( &msg, NULL, 0, 0 ) ){
		TranslateMessage( &msg );
		DispatchMessage( &msg );
	}

	_Module.Term();
	return (int)msg.wParam;
}
