Yield = class("Yield")

function Yield:new(name, expectedProgress, maxStep)
	local y = instance(self)
	y.name = name
	y.start = daisy.getSeconds()
	y.time = daisy.getSeconds()
	y.step = maxStep
	y.progress = 0
	y.expectedProgress = expectedProgress or 0
	return y
end

function Yield:getThredhold()
	if self.step then
		return self.time + self.step
	else
		return self.time + APP.loadingStep
	end
end

function Yield:disable()
	self.disabled = true
end

function Yield:refresh()
	self.time = daisy.getSeconds()
end

function Yield:addProgress(amt)
	self.progress = math.clamp(self.progress + amt, 0, self.expectedProgress)
end

SimpleRoutine = class("SimpleRoutine")

function SimpleRoutine:new(func, maxStep)
	local l = instance(self)
	l.coroutine = coroutine.create(func)
	l.yield = Yield:new("Simple", nil, maxStep)
	l.first = true
	l.tick = 0
	return l, l.yield
end

function SimpleRoutine:step(...)
	if self.coroutine then
		local ok, done, done_2 = nil,nil, nil
		local tick = self.tick
		self.tick = tick + 1 		
		if self.first then
			self.first = false
			ok, done, done_2 = coroutine.resume(self.coroutine, ...)
			if not ok then
				debug.ptb(debug.traceback(self.coroutine, done))
			end
		else
			self.yield:refresh()
			ok, done, done_2 = coroutine.resume(self.coroutine)
			if not ok then
				--print(done)
				debug.ptb(debug.traceback(self.coroutine, done))
			end
		end
		if not ok then
			print(tostring(done)..coroutine.status(self.coroutine))
			self.error = tostring(done).." "..coroutine.status(self.coroutine)
			return nil
		end
		if coroutine.status(self.coroutine) == "dead" then
			self.coroutine = nil
			return done, done_2
		end
	else
		return nil
	end
end

function SimpleRoutine:getError()
	return self.error
end