/*
Copyright 2007, Freie Universitaet Berlin. All rights reserved.

These sources were developed at the Freie Universität Berlin, Computer
Systems and Telematics group.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.

- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
 
- Neither the name of Freie Universitaet Berlin (FUB) nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.

This software is provided by FUB and the contributors on an "as is"
basis, without any representations or warranties of any kind, express
or implied including, but not limited to, representations or
warranties of non-infringement, merchantability or fitness for a
particular purpose. In no event shall FUB or contributors be liable
for any direct, indirect, incidental, special, exemplary, or
consequential damages (including, but not limited to, procurement of
substitute goods or services; loss of use, data, or profits; or
business interruption) however caused and on any theory of liability,
whether in contract, strict liability, or tort (including negligence
or otherwise) arising in any way out of the use of this software, even
if advised of the possibility of such damage.

This implementation was developed by the CST group at the FUB.

For documentation and questions please use the web site
http://scatterweb.mi.fu-berlin.de and the mailinglist
scatterweb@lists.spline.inf.fu-berlin.de (subscription via the Website).
Berlin, 2007
*/

/**
 * @file		ScatterWeb.Cmd.c
 * @brief		Command Engine
 * @ingroup		cmd
 * @version		$Revision: 130 $
 *
 * <p>See <a href="group__cmd.html">Command Engine</a> for documentation.</p>
 *
 * $Id: ScatterWeb.Cmd.c 130 2007-10-31 09:55:51Z baar@PCPOOL.MI.FU-BERLIN.DE $
 */

/**
 * @addtogroup cmd
 * @{
 */

#include <string.h>
#include <ScatterWeb.System.h>
#include "ScatterWeb.Cmd.internal.h"

char	cmd_reply_buffer[1][TERM_BUFSIZE + sizeof(cmd_header_t) + 1];
uint8_t	cmd_buffers_in_use;

void Cmd_on() {
	memset(cmd_reply_buffer, 0, sizeof(cmd_reply_buffer));
	cmd_buffers_in_use = 0;
	System_registerCallback(C_SERIAL, (fp_vp)&Cmd_serialHandler);
}

int Cmd_Run(
		const cmd_header_t (*const	cmd_header),
		const char*					cmd_args,
		const int					size,
		void*						rpl_buffer,
		const int					rpl_buffersize,
		bool						directConnection
) {
	command_t*		pCommand;
	int				headersize;
	int				rpl_size = 0;
	struct cmd_args_unsafe cmdargs;

	headersize = _Cmd_GetHeaderSize(cmd_header);

	cmdargs.request = cmd_header;
	if( cmd_args == NULL )
		cmdargs.args = ((char*)cmd_header) + headersize;
	else
		cmdargs.args = cmd_args;
	cmdargs.arg_size = size - headersize;
	cmdargs.response = (cmd_header_t*)rpl_buffer;
	cmdargs.response_bufsize = rpl_buffersize;

	if( cmd_header->flags & CMD_REQFLAG_REPLY ) {
		// prepare reply
		memcpy(cmdargs.response, cmd_header, headersize);
		cmdargs.response_args = ((char*)cmdargs.response) + headersize;
		*cmdargs.response_args = CHAR_NUL;
	} else {
		cmdargs.response_args = NULL;
		cmdargs.response_bufsize = 0;
	}

	// get flags
	uint8_t			cmdflags;
	cmdargs.response->flags = 0;
	cmdflags = 0;
	if( CMD_IS_ASCII(cmd_header) ) {
		cmdargs.response->flags |= CMD_RPLFLAG_ASCII;
		cmdflags |= CMDFLAG_ASCII;
	}	
	if( directConnection )
		cmdflags |= CMDFLAG_SERIAL;

	// get handler
	pCommand = _Cmd_GetHandler( cmdflags, &cmd_header->id );	

	if( pCommand == NULL ) {
		if( CMD_IS_ASCII(cmd_header) )
			LOG_MEDIUM("(ACMD) ERR: no handler %s", (char*)&cmd_header->id.protocol);
		else
			LOG_MEDIUM("(BCMD) ERR: no handler %u.%u", cmd_header->id.protocol, cmd_header->id.function);

		rpl_size = CMD_ERROR;
	} else {
		// run command
		if( CMD_IS_ASCII(cmd_header) ) {
			pCommand->delegate.ascii((cmd_args_t*)&cmdargs);
			rpl_size = strlen(cmdargs.response_args);
		} else {
			rpl_size = pCommand->delegate.binary((cmd_args_t*)&cmdargs);
		}
	}
	
	if( cmd_header->flags & CMD_REQFLAG_REPLY ) {	
		if( rpl_size < CMD_SUCCESS ) {
			cmdargs.response->flags |= CMD_RPLFLAG_ERROR;
			rpl_size = headersize;
		} else {
			rpl_size += headersize;
		}
	} else {
		rpl_size = 0;
	}
	
	return rpl_size;
}

#if CMD_ASCII_MODE
	uint16_t Cmd_SplitArgs(const char* args) {
		register char*	c;
		register uint16_t	count;
		
		if( *args == CHAR_NUL )
			return 0;	
	
		for( c = (char*)args, count = 1; *c != CHAR_NUL; c++ ) {
			if( *c == CHAR_SPC ) {
				*c = CHAR_NUL;
				count++;
			}
		}
		return count;
	}
	
	const char* Cmd_GetNextArg(const char* arg) {
		register const char* c = arg;
		
		// move along character data
		while( *c > CHAR_SPC ) c++;
		// move along whitespace
		while( *c == CHAR_NUL ) c++;
		
		if( *c == CHAR_ETX ) {
			// end of line
			return NULL;
		} else {
			// next arg
			return c;
		}
	}
#endif

/// Find command handler for a command id/name
command_t* _Cmd_GetHandler(const uint8_t flags, const void* id) {
	extern command_t __term_end;   // __term_end is provided by the linker script, end of .commands segment.
  	extern command_t* _System_firstCommand();
  
  	command_t* c;
	command_t* first = _System_firstCommand();
	command_t* last = &__term_end;
 
 	command_t* handler = NULL;

  #if CMD_ASCII_MODE
	if( (flags & CMDFLAG_ASCII) ) {
				
		for( c = first; c < last; c++ ) {
			if( c->flags & CMDFLAG_ASCII ) {			
				const register char* name1;	// name of stored command
				const register char* name2;	// name to look for
				
				for( name1 = (char*)id, name2 = c->id.ascName; 1; name1++, name2++ ) {
					if( *name2 == CHAR_NUL ) {	// always ended by null
						if( *name1 <= CHAR_SPC ) {	// ended by null or space
							if( !(flags & CMDFLAG_SERIAL) && (c->flags & CMDFLAG_SERIAL) )
								return NULL;	// serial only, but distant source
							else
								return c;
						}
					}
					if( *name1 != *name2 )
						break;					// mismatch, next command
				}
			}
		}	
	} else
  #endif
	{
		for( c = first; c < last; c++ ) {
			if( (c->flags & CMDFLAG_ASCII) == 0 ) {
				if( c->id.binId.protocol == ((struct cmd_binid*)id)->protocol ) {
					if( c->id.binId.function == ((struct cmd_binid*)id)->function ) {
						return c;
					} else if( c->id.binId.function == CMD_FUNCTION_HANDLER ) {
						// keep handler and use this if no more specific function exists
						handler = c;
					}
				}

			}
		}
	}

	return handler;
}

char* _Cmd_GetBuffer() {
	if( cmd_buffers_in_use == 0 ) {
		cmd_buffers_in_use++;
		return cmd_reply_buffer[0];
	} else {
		return NULL;
	}
}

void _Cmd_FreeBuffer(char* buffer) {
	if( cmd_buffers_in_use > 0 )
		cmd_buffers_in_use--;
}

void _Cmd_StateReply(cmd_header_t* buffer, uint8_t state) {
	buffer->id.protocol = CMD_PROTOCOL_STATE;
	buffer->id.function = state;
}

uint16_t _Cmd_GetHeaderSize(const cmd_header_t (*const	pCmd)) {
  #if CMD_ASCII_MODE
	if( CMD_IS_ASCII(pCmd) ) {
		char* cmdname = ((char*)pCmd) + CMD_ASCII_NAME_OFFSET;
		uint16_t namelen = strlen(cmdname) + 1;
		return CMD_ASCII_NAME_OFFSET + namelen;
	}
	else
  #endif
	{
		return sizeof(cmd_header_t);
	}
}

// return system information
BINCMD( CMD_PROTOCOL_SYSTEM, CMD_FUNC_SYSTEM_INFO, CMDFLAG_DEFAULT, cmdargs ) {
	// reply with current node id
	((uint8_t*)cmdargs->response_args)[0] = 0;
	((uint8_t*)cmdargs->response_args)[1] = Configuration.id;
	return sizeof(uint16_t);
}

BINCMD( CMD_PROTOCOL_SYSTEM, CMD_FUNC_SYSTEM_ID, CMDFLAG_DEFAULT, cmdargs ) {
	// see if request has one int argument
	if( cmdargs->arg_size == sizeof(uint16_t) ) {
		// set node id from argument
		Configuration.id = ((uint8_t*)cmdargs->args)[1];
	}

	// reply with current node id
	((uint8_t*)cmdargs->response_args)[0] = 0;
	((uint8_t*)cmdargs->response_args)[1] = Configuration.id;
	return sizeof(uint16_t);
}

#if CMD_ASCII_MODE
	/// test if a character is valid for a command name
	bool _Cmd_IsValidNameChar(char c) {
		if( c < '0' )
			return false;
		if( c <= '9' )
			return true;
		if( c < 'A' )
			return false;
		if( c <= 'Z' )
			return true;
		if( c < '_' )
			return false;
		if( c <= 'z' )
			return true;
		return false;
	}
#endif

#if CMD_ENABLE_LOGGING
void _Cmd_logCommand(
	char type,
	const netaddr_t (*const		pAdr),
	const cmd_header_t (*const	pCmd),
	uint16_t size
) {
  #if ((DEBUGLOG_LEVEL & DEBUGLOG_LEVEL_MASK) >= VERBOSE) 
	
	// direction of pAdr (D = destination, S = source)
	char direction = 'D';
	char* typestring = "req\0rpl\0fwd\0";
	char* t = typestring;

	if( type == 'q' ) {
		direction = 'S';
	} else if( type == 'r' ) {
		t += 4;
	} else {
		t += 8;
	}
	
  #if CMD_ASCII_MODE
	if( CMD_IS_ASCII(pCmd) ) {
		const char* name = ((char*)pCmd) + CMD_ASCII_NAME_OFFSET;
		LOG_VERBOSE("(ACMD) %s %c:%u CMD:%s L:%u F:%.2x",
			t, direction,
			*pAdr,
			name,
			size, pCmd->flags);		
	} else
  #endif
	{
		LOG_VERBOSE("(BCMD) %s %c:%u CMD:%u.%u L:%u F:%.2x",
			t, direction,
			*pAdr,
			pCmd->id.protocol, pCmd->id.function,
			size, pCmd->flags);
	}
				
  #endif
}
#endif

/** @} */
