TimedAction = {}

function TimedAction:updateDelayed(dt) 
	self.countdown = self.countdown - dt
	if self.countdown <= 0 then
    	self.callback()
    end
	
	return self.countdown > 0
end

function TimedAction:updateRepeated(dt)
	self.countdown = self.countdown - dt
	local continue = true
	if self.countdown <= 0 then
		if self.callback() == false then
 		   	continue = false
		end    	
		self.countdown = self.repeatDelay
    end
	
	return continue
end

TimedActionManager = { actions = {}, actionId = 1 }

-- Invokes callback function after specified delay
function TimedActionManager.delayAction(delay, callback) 
	local action = {}
	action.update = TimedAction.updateDelayed
	action.callback = callback
	action.countdown = delay
  
	return TimedActionManager.insertAction(action)
end

-- Invokes callback function repeatedly with specified delay between calls,
-- if callback returns false, the action will be removed
function TimedActionManager.repeatAction(delay, callback) 
	local action = {}
	action.update = TimedAction.updateRepeated
	action.callback = callback
	action.countdown = delay
	action.repeatDelay = delay
	
	return TimedActionManager.insertAction(action)
end

function TimedActionManager.insertAction(action)
	local actionId = TimedActionManager.actionId
	TimedActionManager.actions[actionId] = action
	TimedActionManager.actionId = TimedActionManager.actionId + 1
  
	return actionId
end

function TimedActionManager.removeAction(actionId)
	TimedActionManager.actions[actionId] = nil
end

-- Updates all actions, removes one that finish
function TimedActionManager.update(dt)
	for id,action in pairs(TimedActionManager.actions) do
    	if not action:update(dt) then
			TimedActionManager.removeAction(id)
		end
    end
end
