/*******************************************************************************
 * Copyright (c) 2005, 2007 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 - Initial Implementation
 *
 * $Id: DumpCmdHandler.cpp,v 1.4 2007/05/22 16:21:05 samwai Exp $
 *
 *******************************************************************************/ 

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

DumpCommandHandler::DumpCommandHandler()
{
}

DumpCommandHandler::~DumpCommandHandler()
{
}

void DumpCommandHandler::incomingCommand(INode* node, CommandElement* command)
{
	int            ret = -1;
	int            sourceID;
	int            contextID;
	char*          interfaceName;
	char*          cmdName;
	tptp_list_t*   paramList;

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

	if ( isEqualString( interfaceName, "org.eclipse.tptp.legacy" ))
	{
		if  (isEqualString( cmdName, "customCommand" ))
		{
			char* msg;
			getStringParam( "message", paramList, &msg );
			printf( "Received custom command: %s\n", msg );
			tptp_free( msg );
		}
		else if  (isEqualString( cmdName, "binaryCustomCommand" ))
		{
#ifdef TPTP_BASE64_ENCODING_IMPLEMENTED
			char*	msg;
			char*	data;
			int		dataLen;
			char	dataStr[1024];
			int		i;
			int		len;

			getStringParm( "message", &parmList, &msg );
			printf( "Received binary custom command: %s\n", msg );

			len = tptp_decodeBase64( msg, strlen(msg), NULL, 0 ); /* String needs to pass null to the encoder */
			data = (char*)tptp_malloc(sizeof(char) * len);
			dataLen = tptp_decodeBase64( msg, strlen(msg), data, len );

			strcpy( dataStr, "   Binary data is: " );
			for ( i = 0; i < dataLen; i++ )
			{
				char entry[16];

				if ( i == dataLen-1 )
					sprintf( entry, "%u\n", (unsigned int)data[i] );
				else
					sprintf( entry, "%u, ", (unsigned int)data[i] );

				strcat( dataStr, entry );
			}

			tptp_free(data);
			printf( dataStr );

			tptp_free( msg );
#endif /* TPTP_BASE64_ENCODING_IMPLEMENTED */
		}
	}
	
	tptp_free(interfaceName);
	tptp_free(cmdName);
	tptp_list_clear(paramList);
	tptp_free(paramList);
}
