local function Z(Z,D)return Z.time>D.time end local D={}D.prototype={}D.__index=D.prototype function D.new()local Z={}Z.currentTime=0 Z._tasks={}setmetatable(Z,D)return Z end function D.prototype.schedule(j,D,Q)local O={co=Q,time=j.currentTime+D}table.insert(j._tasks,O)table.sort(j._tasks,Z)end function D.prototype.step(D,Z)D.currentTime=D.currentTime+Z while true do local Z=D._tasks[#D._tasks]if Z==nil or Z.time>D.currentTime then break end D._tasks[#D._tasks]=nil assert(coroutine.resume(Z.co))end end return D
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