/*******************************************************************************
 * Copyright (c) 2005 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: CmdExtractor.c,v 1.8 2005/09/19 21:37:40 akaylor Exp $
 *******************************************************************************/ 

#include "CmdExtractor.h"
#include "tptp/TPTPUtils.h"
#include "CXLog.h"

tptp_int32 createCommandExtractor( tptp_object* cmo, command_extractor_data_t* cxData, tptp_object* cxo )
{
	cx_state_data* cx = NULL;

	/* Check the incoming parameters */
	if ( cxData->logEventEntry == NULL )
	{
		return -1; /* TODO: return a better error */
	}
	if ( cxData->processCommandEntry == NULL )
	{
		/* In this case we can't use our standard macro because it 
		     depends on data we haven't allocated yet            */
		cxData->logEventEntry( cmo, "Command Extractor", COMMAND_EXTRACTOR_ID, __FILE__, __LINE__, TPTP_CRITICAL, "Missing processCommand entry point on createCommandExtractor call." );
		return -1;
	}

	/* Allocate our state data */
	cxo->data = tptp_malloc( sizeof(cx_state_data) );
	if ( cxo->data == NULL )
	{
		if ( cxData->logEventEntry != NULL )
		{
			/* In this case we can't use our standard macro because it 
			     depends on the data we just failed to allocate            */
			cxData->logEventEntry( cmo, "Command Extractor", COMMAND_EXTRACTOR_ID, __FILE__, __LINE__, TPTP_CRITICAL, "Unable to allocate state memory." );
		}
		return -1;
	}
	else
	{
		cx = (cx_state_data*) cxo->data;
	}

	/* Store the Agent Controller entry points */
	cx->ac.cmo            = cmo;
	cx->ac.processCommand = cxData->processCommandEntry;
	cx->ac.logEvent       = cxData->logEventEntry;

	/* Initialize the flag to recognize our component */\
	cxo->objectID = COMMAND_EXTRACTOR_ID;

	initializeParser();

	return 0;
}

tptp_int32 destroyCommandExtractor( tptp_object* cxo )
{
	/* Check the incoming parameter */
	if ( cxo == NULL )
		return -1;

	/* TODO: Perform any additional clean up */

	/* Free our state data */
	tptp_free( cxo->data );

	/* Clear out the object data */
	cxo->data = 0;
	cxo->objectID = -1;

	return 0;
}

tptp_int32 processMessage( tptp_object* cxo, tptp_uint32 size, const tptp_string* message )
{
	cx_state_data* cx = (cx_state_data*)cxo->data;

	/* Check the incoming parameter */
	if ( cx == NULL )
		return -1;

	/* Extract the commands and destination IDs                 */
	/* The Agent Controller will be called within this function */
	return parseMessage( cx, message );
}


