#include "ecs_component.h"

/* Returns a component of type. */
void*
ecs_component_get(ECS* ecs, ECSComponentType type, u32 id)
{
	return ecs_component_list_get(&ecs->lists[type], id);
}

/* Returns a component, given an index, instead. */
void*
ecs_component_from_index_get(ECS* ecs, ECSComponentType type, u32 index)
{
	return vector_get(&ecs->lists[type].components, index);
}

/* Adds and returns a new component, executing system's add function. */
void*
ecs_component_add(ECS* ecs, ECSComponentType type, u32 id)
{
	void* component;
	ECSFunction add;

	component = vector_push(&ecs->lists[type].components, NULL);

	memcpy(component, (void*)&id, sizeof(u32));

	add = ecs->lists[type].system.functions[ECS_FUNCTION_ADD];


	if (add)
		add(component, ecs);

	return component;
}

/* Deletes a component, given a valid id. */
void
ecs_component_delete(ECS* ecs, ECSComponentType type, u32 id)
{
	for (s32 i = 0; i < (s32)ecs->lists[type].components.count; i++)
	{
		u32 checkID;
		void* component;

		component = vector_get(&ecs->lists[type].components, i);

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

		if (checkID == id)
		{
			ECSFunction delete;

			delete = ecs->lists[type].system.functions[ECS_FUNCTION_DELETE];

			if (delete)
				delete(component, ecs);

			vector_remove(&ecs->lists[type].components, i);
		}
	}
}
