/*******************************************************************************
 * Copyright (c) 2006 Intel Corporation.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    Andy Kaylor, Intel - Created Ping test
 *
 * $Id: PingCmdHandler.cpp,v 1.2 2006/10/26 21:31:56 kcallaghan Exp $
 *
 *******************************************************************************/ 

#include "PingCmdHandler.h"
#include "tptp/TPTPUtils.h"

PingCommandHandler::PingCommandHandler()
{
	responseReceived = false;
	tptp_initializeSemaphore(&responseReceivedSem);
}

PingCommandHandler::~PingCommandHandler()
{
	tptp_deleteSemaphore(&responseReceivedSem);
}				
				
void PingCommandHandler::incomingCommand(INode* node, CommandElement* command)
{
	int            ret = -1;
	char*          cmdName=0;
	int            sourceID;
	int            contextID;
	char*          interfaceName=0;
	tptp_list_t*   paramList=0;

	ret = parseCommand(command->getCommand(), &sourceID, &contextID, &interfaceName, &cmdName, &paramList );

	if (isEqualString(cmdName, "pingResponse"))
	{
		static int count = 0;

		count++;

		if ( count == 100 )
		{
			printf("r");
			count = 0;
		}
	}
	else
	{
		printf("\nUnexpected response received.\n");
	}

	responseReceived = true;
	tptp_postSemaphore(&responseReceivedSem);

	// Free space allocated by parseCommand()
	if (ret != -1)
	{
		if (interfaceName)
			tptp_free(interfaceName);
		if (cmdName)
			tptp_free(cmdName);
		if(paramList)
		{
			tptp_list_clear(paramList);
			tptp_free(paramList);
		}
	}
}

void PingCommandHandler::waitForResponse()
{
	while ( !responseReceived )
	{
		tptp_waitSemaphore( &responseReceivedSem );
	}

	responseReceived = false;	
}
