-- Adds a service to this provider only

function ServiceBag:_addServiceType(serviceType)
	if not self._serviceTypesToInitializeSet then
		error(("Already finished initializing, cannot add %q"):format(tostring(serviceType)))
		return
	end

	-- Already added
	if self._services[serviceType] then
		return
	end

	-- Construct a new version of this service so we're isolated
	local service = setmetatable({}, { __index = serviceType })
	self._services[serviceType] = service

	self:_ensureInitialization(serviceType)
end

function ServiceBag:_ensureInitialization(serviceType)
	if self._initializedServiceTypeSet[serviceType] then
		return
	end

	if self._initializing then
		self._serviceTypesToInitializeSet[serviceType] = nil
		self._initializedServiceTypeSet[serviceType] = true
		self:_initService(serviceType)
	elseif self._serviceTypesToInitializeSet then
		self._serviceTypesToInitializeSet[serviceType] = true
	else
		error("[ServiceBag._ensureInitialization] - Cannot initialize past initializing phase ")
	end
end

function ServiceBag:_initService(serviceType)
	local service = assert(self._services[serviceType], "No service")

	if service.Init then
		local current
		task.spawn(function()
			current = coroutine.running()
			service:Init(self)
		end)

		assert(coroutine.status(current) == "dead", "Initializing service yielded")
	end

	table.insert(self._serviceTypesToStart, serviceType)
end
