local statemonitor={}

local callbacks={}

local function ternary(val, t, f)
	if val then return t else return f end
end

--- Deregister a callback
---@param name string Name of callback
function statemonitor.deregister(name)
	callbacks[name] = nil
end

--- Register a callback to a function
--Registers a callback to run when a check funciton evaluates to true
---@param name string Name of callback
---@param check function Function to evaluate
---@param callback function Callback to run when true
---@param frequency? integer Frequency to run the check, in ticks (default 5)
---@param once? boolean Whether the callback should be deregistered after running once, default true
function statemonitor.register(name, check, callback, frequency, once)
	frequency=frequency or 5
	once=ternary(once ~= nil, once, true)
	assert(type(callback)=="function")
	assert(type(check)=="function")
	callbacks[name] = {check=check, callback=callback, f=frequency,
	deregister=once}
end

local function tick()
	for k, v in pairs(callbacks) do
		if world.getTimeOfDay() % v.f and v.check() then
			v.callback()
			if v.deregister then
				statemonitor.deregister(k)
			end
		end
	end
end

events.TICK:register(tick, "nulllib.statemonitor")


return statemonitor