
#include "function.h"



struct functionLayout * function_getFunctionByName( struct array * functions, char * functionName ) {

	int count 				= array_length( functions );

	for (int i = 0; i < count; ++i)
	{
		struct functionLayout * currentFunction = array_get( functions, i );

		if( strcmp( currentFunction->name, functionName ) == 0 ) {

			return currentFunction;

		}

	}

	return NULL;

}

char * function_getReturnTypeBySymbol( char * functionName, int * leftSideIsPointer ) {

	struct functionLayout * currentFunction 		= function_getFunctionByName( allFunctions, functionName );

	if( currentFunction != NULL ) {

		struct array * functionDeclarationParts		= text_split( currentFunction->declarationText, " \t" );

		*leftSideIsPointer	= variable_isPointer( functionDeclarationParts );

		return array_get( functionDeclarationParts, 0 );

	} else {

		return NULL;

	}

}

void cloneMethodToFunction( struct method * currentMethod, struct array * functions,  char * newName ) {

	struct text * newMethodDecleration = text_new( "" );

	text_append( newMethodDecleration, currentMethod->returnType );

	text_append( newMethodDecleration, " " );

	text_append( newMethodDecleration, newName);


	struct array * arguments 	= array_new();

	int argumentCount 			= array_length( currentMethod->arguments );

	for ( int k = 1; k < argumentCount; ++k )
	{
		
		char * currentArgument = array_get( currentMethod->arguments, k );

		array_add( arguments, currentArgument );

	}


	struct functionLayout * functionInstance 	= malloc( sizeof( struct functionLayout ) );

	functionInstance->name 						= newName;

	functionInstance->declarationText			= newMethodDecleration->value;

	functionInstance->bodyOriginal				= currentMethod->bodyOriginal;

	functionInstance->variables					= array_new();

	functionInstance->body						= method_parse( currentMethod->bodyOriginal, functionInstance->variables, functions );//;

	functionInstance->arguments 				= arguments;

	functionInstance->lineNumber				= -1;


	array_add( functions, functionInstance ); 

}


int functionExists( struct array * functions, char * functionName ) {

	int count 				= array_length( functions );

	for (int i = 0; i < count; ++i)
	{
		
		struct functionLayout * currentFunction = array_get( functions, i );

		if( strcmp( currentFunction->name, functionName ) == 0 ) {

			return 1;

		}

	}

	return -1;

}