/*
    Copyright 2004-2005 Electronic Arts Inc.
*/

#include "GameTalk/bFunk/GameTalkProtocol.h"
#include "bFunk.hpp"

using namespace EA;

GameTalkProtocol* GameTalkProtocol::mInstance = NULL;

GameTalkProtocol::GameTalkProtocol(const char* const ipAddress, const int port)
:
IGameTalkProtocol(ipAddress, port)
{
	mInstance = this;

	// Create a bFunc server...
	mServer = new("GameTalkProtocol") bFunkServerPlatform("gametalk_game");

	// and add a message handler.
	mServer->AddASync(0, GameTalkProtocol::HandleBFuncMessage);
}

GameTalkProtocol::GameTalkProtocol(const int port)
:
IGameTalkProtocol(port)
{
	mInstance = this;

	// Create a bFunc server...
	mServer = new("GameTalkProtocol") bFunkServerPlatform("gametalk_game");

	// and add a message handler.
	mServer->AddASync(0, GameTalkProtocol::HandleBFuncMessage);
}

GameTalkProtocol::~GameTalkProtocol()
{
	// Don't need the bFunc server anymore
	delete mServer;

	mInstance = NULL;
}

int GameTalkProtocol::Poll()
{
	bFunkService();
	// Need to get above to return amount of data received
	return 0;
}

bool GameTalkProtocol::Send(void* buffer, size_t msgSize)
{
	if (0 != msgSize)
	{
		// Send the message to bFunc
		bFunkCallASync("gametalk_codeine", 0, buffer, static_cast<int>(msgSize));

		return true;
	}
	return false;
}

bool GameTalkProtocol::Connect()
{
	// This protocol needs to be updated to support graceful reconnect!
	return false;
}

void GameTalkProtocol::HandleBFuncMessage(const void* buffer, int size)
{
	if (mInstance->mParser != NULL)
	{
		mInstance->mParser->DigestReceivedData((char*)buffer, size);
	}
}

