

exord_core.events_list = {}

exord_core.Event = {
    event_time = 0,
}
exord_core.Event.__meta = {__index = exord_core.Event}


local function add(self)
    table.insert(exord_core.events_list, self)
end

local function remove(self)
    local i = table.indexof(exord_core.events_list, self)
    if i > 0 then
        exord_core.events_list[i] = nil
    end
end

function exord_core.Event:_on_step(dtime)
    if not self._init then
        self._init = true
        if self.on_start then
            self:on_start()
        end
    end
    self.event_time = self.event_time + dtime
    if self.on_step then
        self:on_step(dtime)
    end
    if self.removed then
        remove(self)
        if self.on_end then
            self:on_end()
        end
    end
end

function exord_core.Event:remove()
    self.removed = true
end


function exord_core.Event.new(def)
    if def then def = table.copy(def)
    else def = {} end
    local self = setmetatable(def, exord_core.Event.__meta)
    add(self)
end

function exord_core.event_on_step(dtime)
    for i, event in ipairs(exord_core.events_list) do
        event:_on_step(dtime)
    end
end

minetest.register_globalstep(exord_core.event_on_step)

exord_core.registered_events = {}
function exord_core.register_event(name, def)
    exord_core.registered_events[name] = def
end

function exord_core.start_event(name)
    local def = exord_core.registered_events[name]
    if not def then return end
    return exord_core.Event.new(def)
end

exord_core.register_event("test", {
    on_step = function(self, dtime)
        core.log("test step")
        if self.event_time > 0.1 then
            self:remove()
        end
    end,
    on_start = function(self)
        core.log("test start")
    end,
    on_end = function(self)
        core.log("test end")
    end,
})

-- minetest.after(5, exord_core.start_event, "test")