#include "ecs_component_list.h"

/* From ECSComponentInfo, initialize a component list. */
void
ecs_component_list_init(ECSComponentList* self, ECS* ecs, ECSComponentInfo info)
{
	self->ecs = ecs;
	self->type = info.type;
	self->system = info.system;
	vector_init(&self->components, info.size);
}

/* Executes a function on a component list. */
/* Exits if component list has a NULL function. */
void
ecs_component_list_function(ECSComponentList* self, ECSFunctionType type)
{
	ECSFunction function;

	function = self->system.functions[type];

	if (!function)
		return;

	for (s32 i = 0; i < (s32)self->components.count; i++)
	{
		void* component;
		ECSComponent ecsComponent;

		component = vector_get(&self->components, i);

		memcpy(&ecsComponent, component, sizeof(ECSComponent));

		if 
		(
			ecsComponent.isDisabled ||
			ecsComponent.isFunctionDisabled[type]
		)
			continue;

		function(component, self->ecs);
	}
}

/* Returns a component within the component list, given an id. */
void*
ecs_component_list_get(ECSComponentList* self, u32 id)
{
	for (s32 i = 0; i < (s32)self->components.count; i++)
	{
		u32 checkID;
		void* component;

		component = vector_get(&self->components, i);

		memcpy(&checkID, component, sizeof(u32));

		if (checkID == id)
			return component;
	}

	return NULL;
}

/* Clears all elements in a component list. */
void
ecs_component_list_clear(ECSComponentList* self)
{
	vector_clear(&self->components);
}

/* Frees a component list. */
void
ecs_component_list_free(ECSComponentList* self)
{
	vector_free(&self->components);
	memset(self, '\0', sizeof(ECSComponentList));
}
