local function H(H,u)return H.time>u.time end local u={}u.prototype={}u.__index=u.prototype function u.new()local H={}H.currentTime=0 H._tasks={}setmetatable(H,u)return H end function u.prototype.schedule(R,u,Q)local O={co=Q;time=R.currentTime+u}table.insert(R._tasks,O)table.sort(R._tasks,H)end function u.prototype.step(u,H)u.currentTime=u.currentTime+H while true do local H=u._tasks[#u._tasks]if H==nil or H.time>u.currentTime then break end u._tasks[#u._tasks]=nil assert(coroutine.resume(H.co))end end return u
local function taskCompare(a, b)
	return a.time > b.time
end

local TaskScheduler = {}
TaskScheduler.prototype = {}
TaskScheduler.__index = TaskScheduler.prototype

function TaskScheduler.new()
	local self = {}

	self.currentTime = 0
	self._tasks = {}

	setmetatable(self, TaskScheduler)

	return self
end

function TaskScheduler.prototype:schedule(delay, co)
	local task = {
		co = co,
		time = self.currentTime + delay,
	}

	table.insert(self._tasks, task)
	table.sort(self._tasks, taskCompare)
end

function TaskScheduler.prototype:step(deltaTime)
	self.currentTime = self.currentTime + deltaTime

	while true do
		local top = self._tasks[#self._tasks]

		if top == nil or top.time > self.currentTime then
			break
		end

		self._tasks[#self._tasks] = nil
		assert(coroutine.resume(top.co))
	end
end

return TaskScheduler