/*
    Copyright (C) 1998, 1999 by Serguei 'Snaar' Narojnyi
    Copyright (C) 1998, 1999 by Jorrit Tyberghein
    Written by Serguei 'Snaar' Narojnyi

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public
    License along with this library; if not, write to the Free
    Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

#include "sysdef.h"
#include "ndrvdemo/core.h"
#include "inetdrv.h"

char appname[] = "Crystal Space Network Driver Demo: Server";

DWORD dwListeningSocket;
DWORD dwServerSocket;

DWORD dwLastAccept = 0;
bool bConnected = 0;

void DoSomething()
{
	DWORD dwSize = 512;
	DWORD retval;
	char buf[512];

	retval = Sys->piNetDrv->Receive(dwServerSocket, &dwSize, buf);

	if(retval == S_FALSE)
	{
		Sys->Printf(MSG_INITIALIZATION, "Receive error %i\n", Sys->piNetDrv->GetLastError());
	}
	else
	{
		Sys->piNetDrv->Send(dwServerSocket, dwSize, buf);
		Sys->piNetDrv->Kill(dwServerSocket);

		buf[dwSize - 2] = '\n';
		buf[dwSize - 1] = '\0';

		Sys->Printf(MSG_INITIALIZATION, buf);

		bConnected = false;
	}
}

void App::NextFrame(long elapsed_time, long current_time)
{
	SysSystemDriver::NextFrame(elapsed_time, current_time);

//  Sys->Printf (MSG_INITIALIZATION, ".\n");

	CS_NET_ADDRESS addr;

	if(!bConnected)
	{
		if((Sys->Time() - dwLastAccept) > 1000)
		{
			dwLastAccept = Sys->Time();
			if(Sys->piNetDrv->Accept(dwListeningSocket, &dwServerSocket, &addr) != S_FALSE)
			{
				bConnected = true;
				Sys->Printf(MSG_INITIALIZATION, "Connection Accepted\n");
			}
			else
			{
				Sys->Printf(MSG_INITIALIZATION, "Accept error %i\n", Sys->piNetDrv->GetLastError());
			}
		}
	}
	else
	{
		DoSomething();
	}

	csEvent *Event;
	while ((Event = Sys->EventQueue->Get ()) != NULL)
	{
		switch (Event->Type)
		{
		case csevKeyDown:
			if(Event->Key.Code == CSKEY_ESC) System->Shutdown = true;
			break;
		}
		CHK (delete Event);
	}
}

void InitNet()
{
	dwLastAccept = Sys->Time();
	DWORD retval;
	
	retval = Sys->piNetDrv->Spawn(&dwListeningSocket, CS_NET_CONNORIENTED);
	
	if(retval == S_FALSE)
	{
		Sys->Printf(MSG_INITIALIZATION, "Spawn error %i\n", Sys->piNetDrv->GetLastError());
	}

	CS_NET_LISTENPARAMS ListenParams;
	ListenParams.port = 2222;

	retval = Sys->piNetDrv->SetListenState(dwListeningSocket, &ListenParams);

	if(retval == S_FALSE)
	{
		Sys->Printf(MSG_INITIALIZATION, "SetListenState error %i\n", Sys->piNetDrv->GetLastError());
	}
}
