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