/*************************************************************************************************************
This file contains accepting conections and disconecting client
2012/6 by Dlxko
**************************************************************************************************************/
#include "AcpDisClient.h"

/************* ACCEPTING CONNECTIONS **************/
void function_accept_connections()
{
	// If empty slots for connection continue
	if (clients_connected < MAX_CLIENTS)
	{
		// Look for avivable connections
		for ( int j = 0; j < MAX_CLIENTS; j++ )
		{
			// If not connected continue
			if (!client[j].connected)
			{
				// Try to accept this client
				if (function_accept_client (&client[j]))
				{
					// Increase the clients count
					clients_connected++;

					// Get IP adress for massage
					char *client_ip_address = inet_ntoa ( client[j].address.sin_addr );

					// Print message
					std::cout << color(FOREGROUND_RED|FOREGROUND_BLUE) << "|SYS|->>"
						<< color(FOREGROUND_GREEN|FOREGROUND_GREEN)
						<< "Accept conn to array pos. ["
						<< color(FOREGROUND_GREEN|FOREGROUND_RED)
						<< j
						<< color(FOREGROUND_GREEN|FOREGROUND_GREEN)
						<< "] from IP adress ["
						<< color(FOREGROUND_GREEN|FOREGROUND_RED)
						<< client_ip_address << color(FOREGROUND_GREEN|FOREGROUND_GREEN)
						<< "]" << white << endl;
				}
			}
		}
	}
}

/************** DISCONNECTING CLIENT **************/
void function_disconnect_client ( _client *current_client )
{
	// Only if connected
	if ( current_client->connected == TRUE )
		closesocket ( current_client->socket );

	// Update client state
	current_client->connected = FALSE;

	// Clear the address length
	current_client->address_length = -1;

	// Decrease number of connected clients
	clients_connected--;

	// Cleaup structure
	current_client->client_acess = 0;

	//Clean name
	memset(current_client->nick_name, 0, 10);

	// Write disconect massage
	std::cout << color(FOREGROUND_RED|FOREGROUND_BLUE) << "|SYS|->>"
		<< color(FOREGROUND_GREEN|FOREGROUND_GREEN)
		<< "Disconnect cln with sock ["
		<< color(FOREGROUND_GREEN|FOREGROUND_RED)
		<< current_client->socket
		<< color(FOREGROUND_GREEN|FOREGROUND_GREEN)
		<< "]"
		<< white << endl;
}