
#include "template.h"


struct template * template_new() {

	struct template * templateInstance 	= malloc( sizeof( struct template ) );

	templateInstance->instances			= array_new();

	return templateInstance;

}


void template_add_arguments( struct template * currentTemplate, char * argumentText ) {

	printf("add arguments to template\n\n\n");

	currentTemplate->arguments = text_split( argumentText, "," );

}

bool template_validateArguments( struct template * currentTemplate, char * argumentText ) {

	array * argumentsArray = text_split( argumentText, "," );

	if( array_length( argumentsArray ) ==  array_length( currentTemplate->arguments ) ) {

		return true;

	} else {

		return false;

	}

}

bool template_addArgumentValue( struct class * classInstance, char * templateArguments ) {

	templateArguments					= text_regexReplaceAll( templateArguments, "struct ", "struct ", "" );

	if( !template_validateArguments( classInstance->template, templateArguments ) ) {

		printf("Error:	Invalid template arguments.		%s \n\n", templateArguments);

		return false;

	}

	if( !template_instanceExists( classInstance->template, templateArguments ) ) {

		printf("Adding template instance. \n\n");

		template_addInstance( classInstance->template, templateArguments );

		template_instanceExists( classInstance->template, templateArguments );

	}

	return true;

}


char * template_extractTemplateName( struct template * currentTemplate, char * argumentText ) {

	array * argumentsArray = text_split( argumentText, "," );

	if( array_length( argumentsArray ) > 0 ) {

		return array_get( argumentsArray, 0 );

	}

	return NULL;

}

bool template_instanceExists( struct template * currentTemplate, char * argumentText ) {

	array * argumentsValueArray 	= text_split( argumentText, "," );

	array * intances				= currentTemplate->instances;

	int count						= array_length( intances );

	for (int i = 0; i < count; ++i)
	{
		
		struct templateInstance * currentTemplateInstance 			= array_get( intances, i );

		array * templateArgumentValues	= currentTemplateInstance->argumentValues;

		int propertyCount				= array_length( templateArgumentValues );

		bool allPropertiesMatch			= true;

		for (int j = 0; j < propertyCount; ++j )
		{
			
			char * currentArgumentValue		= array_get( templateArgumentValues, j );

			char * ArgumentValue			= array_get( argumentsValueArray, j );

			if( strcmp( currentArgumentValue, ArgumentValue ) != 0 ) {

				allPropertiesMatch = false;

			}

		}

		if( allPropertiesMatch ) {

			return true;

		}

	}

	return false;

}


void template_addInstance( struct template * currentTemplate, char * argumentText ) {


	struct templateInstance	* newInstance 	= templateInstance_new();

	newInstance->argumentValues					= text_split( argumentText, "," );

	array_add( currentTemplate->instances, newInstance );


}

//templateInstance_new
