#include <stdio.h>
#include <unistd.h>
#include "server.h"
#include "client.h"
#include "log.h"

FoWebServer::FoWebServer() {
	LogMessage( "web server instanted" );
}

void FoWebServer::Init() {
	num_of_clients = 0;
	FSSOCKET_Initialize();
	char ipaddress[]="127.0.0.1";
	listen_socket = FSSOCKET_Listen( ipaddress , 8080 , NULL );
	LogMessage( "web server initialized" );
	server_mutex = FoCreateMutex( NULL , FALSE , NULL );
}

void FoWebServer::GrabMutex() {
	FoWaitForSingleObject( server_mutex , INFINITE );
}

void FoWebServer::ReleaseMutex() {
	FoReleaseMutex( server_mutex );
}
void client_thread( LPVOID param ) {
	FoClient *client = (FoClient *)param;
	client->HandleClient();
	delete client;
}

void FoWebServer::Stop() {
	SOCKET tempsock = listen_socket;
	listen_socket = INVALID_SOCKET;
	FSSOCKET_HardClose( tempsock , NULL );
}

void FoWebServer::Do( FOHANDLE quit_event ) {
	char ipaddress[]="127.0.0.1";
	if (listen_socket==INVALID_SOCKET) return;
	while (FoWaitForSingleObject( quit_event , 0 )!=WAIT_OBJECT_0) {
		SOCKADDR client_address;
		SOCKET sock = FSSOCKET_Accept( listen_socket , &client_address , NULL );
		if (sock==INVALID_SOCKET) {
			usleep( 10000 );
			continue;
		}

		FoClient *client_thread_instance = new FoClient( sock , this );
		DWORD thread_id;
		FOHANDLE client_thread_handle = FoCreateThread( NULL , 0 , (LPTHREAD_START_ROUTINE) client_thread,
			client_thread_instance ,
			0 , &thread_id );
		FoCloseHandle( client_thread_handle );
	}
}

void FoWebServer::Deinit() {
	LogMessage( "web server deinitialized" );
	if (listen_socket==INVALID_SOCKET) return;
	FSSOCKET_Close( listen_socket , NULL );
}

