-- scheduledEvents by MauScripts
scheduledEvents = {}

-- Function to execute and handle all scheduled events
function execScheduledEvents(timerName)
    local currentTime = os.clock()
    local timerEvents = scheduledEvents[timerName].events
    for i = #timerEvents, 1, -1 do
        local event = timerEvents[i]
        if currentTime >= event.timeToTrigger then
            event.callback()
            table.remove(timerEvents, i)
        end
    end
    if #timerEvents == 0 then
        destroyTimer(timerName)
		scheduledEvents[timerName] = nil
    end
end

-- Function to remove scheduled event by name
function removeScheduledEvents(timerName)
	if scheduledEvents[timerName] then 
		local timerEvents = scheduledEvents[timerName].events
		for i = #timerEvents, 1, -1 do
			table.remove(timerEvents, i)
		end
		if #timerEvents == 0 then
			destroyTimer(timerName)
			scheduledEvents[timerName] = nil
		end
	end
end

-- Function to create a new timer for a scheduled event
function scheduleEvent(timerName, seconds, callback, ...)
    if not scheduledEvents[timerName] then
	    local args = {...}
        scheduledEvents[timerName] = {events = {}}
        scheduledEvents[timerName].timer = Timer(timerName, function() execScheduledEvents(timerName) end, 500, true)
		local event = {
			timeToTrigger = os.clock() + seconds,
			callback = function() callback(unpack(args)) end
		}
		table.insert(scheduledEvents[timerName].events, event)
		--print("scheduleEvent", timerName)
    end
end

