/*************************************************************************************************************
This file contains accepting and receiving client
2012/6 by Dlxko
**************************************************************************************************************/
#include "AcpRcvClient.h"

/********************* ACCEPTING CLIENTS ************************/
bool function_accept_client ( _client *current_client )
{
	// Get adress lenght
	current_client->address_length = sizeof( sockaddr );

	// Get socket
	current_client->socket = accept(server_socket, (sockaddr *) &current_client->address, &current_client->address_length);

	// No data in socket
	if (current_client->socket == INVALID_SOCKET || current_client->socket == SOCKET_ERROR)
		return false;
	else
	{
		// Define as connected
		current_client->connected = TRUE;

		//Save socket info
		FD_ZERO ( &current_client->socket_data );
		FD_SET ( current_client->socket, &current_client->socket_data );

		// Print message
		std::cout << color(FOREGROUND_RED|FOREGROUND_BLUE) << "|SYS|->>"
			<< color(FOREGROUND_GREEN|FOREGROUND_GREEN)
			<< "Accept cln connect with sock ["
			<< color(FOREGROUND_GREEN|FOREGROUND_RED)
			<< current_client->socket << color(FOREGROUND_GREEN|FOREGROUND_GREEN)
			<< "]"
			<< white << endl;

		return true;
	}

	return false;
}

/************************ RECEIVING CLIENTS ***************************/
bool function_receive_client ( _client *current_client, char *buffer, int size )
{
	// Check if socket is member of socket data
	if (FD_ISSET ( current_client->socket, &current_client->socket_data))
	{
		// Clean buffer
		memset(buffer,0,256);

		// Recive data in bytes
		current_client->address_length = recv(current_client->socket, buffer, size, 0);

		// If no bytes it looks like error on client side
		if (current_client->address_length == 0)
		{
			// Disconect
			function_disconnect_client (current_client);
			function_show_warning("Can't receive data from client. Disconecting!");
			return false;
		}

		// If negative bytes return false
		if (current_client->address_length < 0)
			return false;

		// Everything ok
		return true;
	}

	return false;
}