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