-- Maid object:


local Maid = {
	-- _cleanup_tasks = {},
	-- _is_cleaned = false,
}
Maid.__index = Maid

function Maid:AddCleanupTask(task)
	if self._is_cleaned == true then
		PerformCleanupTask(task)
		return function() end
	elseif type(task) == "function" then
		table.insert(self._cleanup_tasks, task)
	elseif typeof(task) == "RBXScriptConnection" then
		table.insert(self._cleanup_tasks, task)
	elseif typeof(task) == "Instance" then
		table.insert(self._cleanup_tasks, task)
	elseif type(task) == "table" then
		if type(task.Destroy) == "function" then
			table.insert(self._cleanup_tasks, task)
		elseif type(task.Disconnect) == "function" then
			table.insert(self._cleanup_tasks, task)
		else
			error("[MadworkMaid]: Received object table as cleanup task, but couldn't detect a :Destroy() method")
		end
	else
		error("[MadworkMaid]: Cleanup task of type \"" .. typeof(task) .. "\" not supported")
	end
	return function(...)
		self:RemoveCleanupTask(task)
		PerformCleanupTask(task, ...)
	end
end

function Maid:RemoveCleanupTask(task)
	local cleanup_tasks = self._cleanup_tasks
	local index = table.find(cleanup_tasks, task)
	if index ~= nil then
		table.remove(cleanup_tasks, index)
	end
end

function Maid:CleanupOfOne(task, ...)
	self:RemoveCleanupTask(task)
	PerformCleanupTask(task, ...)
end

function Maid:Cleanup(...)
	for _, task in ipairs(self._cleanup_tasks) do
		PerformCleanupTask(task, ...)
	end
	self._cleanup_tasks = {}
	self._is_cleaned = true
end
