/*
 * rmpaProtocol.cpp
 *
 * Gouverneur Th. - Cuisinier Gi.
 *
 * Define the protocol server-side RMPA
 * and his implementation.
 */

#include <rmpaProtocol.h>
#include <serverProtocol.h>


void RMPAProtocol::cmdLClients (Message *m)
{
	Message answer;
	answer.numRequest = m->numRequest;
	answer.ident = "Siege central RMPA";
	answer.token = "LCLIENTS";
	
	int count = 0;
	for (int i=0; i<ServerProtocol::listUser.Size(); i++)
		if (ServerProtocol::listUser[i]->getAuth())
			count++;
	answer.args.Push(Message::numToString(count));

	if (m->sC)
		*(m->sC) << answer.serialize();
	else
		throw Exception("Cannot reach other side, pointer NULL...");
	
	for (int i=0; i< ServerProtocol::listUser.Size();i++)
	{
		User *u = ServerProtocol::listUser[i];
		if (u->getAuth())
		{
			Message ans;
			ans.numRequest = m->numRequest;
			ans.ident = "Siege central";
			ans.token = "LCLIENTS";
			ans.args.Push(u->getConn()->getIp());
			ans.args.Push(u->getLogin());
		
			if (m->sC)
				*(m->sC) << ans.serialize();
			else
				throw Exception("Cannot reach other side, pointer NULL...");
		}
	}
	return;
}


void RMPAProtocol::cmdSusps (Message *m)
{
	Message answer;
	answer.numRequest = m->numRequest;
	answer.ident = "Siege central RMPA";
	answer.token = "SUSPS";
	ServerProtocol::suspended = !ServerProtocol::suspended;
	answer.args.Push(string("OK"));
	answer.args.Push((ServerProtocol::suspended)?string("Server is now paused."):string("Server is now back online."));
	if (m->sC)
		*(m->sC) << answer.serialize();
	else
		throw Exception("Cannor reach other side, pointer NULL...");

	return;
}


void RMPAProtocol::cmdStops (Message *m)
{
	Message answer;
	answer.numRequest = m->numRequest;
	answer.ident = "Siege central RMPA";
	answer.token = "STOPS";
	
	if (m->args.Size() != 1)
		answer.args.Push(string("NOK"));
	else
	{
		if (atoi(m->args[0].c_str()) >= 0)
		{
			answer.args.Push(string("OK"));
			ServerProtocol::shutdown = time(0) + atoi(m->args[0].c_str());
		}
	}
	if (m->sC)
		*(m->sC) << answer.serialize();
	else
		throw Exception("Cannor reach other side, pointer NULL...");

	return;
}
	
