#include <psemek/ecs/detail/entity_list.hpp>
#include <psemek/util/assert.hpp>

namespace psemek::ecs::detail
{

	entity_id entity_list::create(table * table, std::uint32_t row)
	{
		if (free_ids_.empty())
			allocate_ids();

		auto id = free_ids_.back();
		free_ids_.pop_back();

		auto & data = entities_[id];
		assert(data.table == nullptr);

		data.table = table;
		data.row = row;

		return id;
	}

	void entity_list::destroy(entity_id id)
	{
		auto & data = entities_[id];
		assert(data.table != nullptr);

		data.table = nullptr;
		data.epoch += 1;

		free_ids_.push_back(id);
	}

	void entity_list::allocate_ids()
	{
		auto old_size = entities_.size();
		entities_.resize(std::max<std::size_t>(1024, entities_.size() * 2));
		for (std::size_t id = entities_.size(); id --> old_size;)
			free_ids_.push_back(id);
	}

}
