
-- in case no aom_wield, imitate it loosely
if minetest.get_modpath("aom_wield") ~= nil then return end

local pl = {}

local function check_player(player)
    if not pl[player] then pl[player] = {} end
    return pl[player]
end

minetest.register_globalstep(function(dtime)
    for i, player in ipairs(minetest.get_connected_players()) do repeat
        local wstack = player:get_wielded_item()
        local wdef = wstack:get_definition()
        -- don't do anything more if no callbacks, but do one test after
        local has_callbacks = (wdef.on_step ~= nil) or (wdef.on_select ~= nil) or (wdef.on_deselect ~= nil)
        if not has_callbacks and (pl[player] == nil) then
            break
        end
        local pi = check_player(player)

        local diff_item = (pi.lstack == nil) or (not pi.lstack:equals(wstack))
        if diff_item and pi.ldef and pi.ldef.on_deselect then
            pi.ldef.on_deselect(pi.lstack, player)
        end

        if diff_item and wdef.on_select then
            wdef.on_select(wstack, player)
        end

        if wdef.on_step then
            wdef.on_step(wstack, player, dtime)
        end

        -- no need to keep track anymore
        if not has_callbacks then
            pl[player] = nil
        else
            pi.lstack = wstack
            pi.ldef = wdef
        end
    until true end
end)
