
aom_inventory.registered_formspec_addons = {}
local fs_addons = aom_inventory.registered_formspec_addons
function aom_inventory.register_formspec_process(in_formspec, tag, func)
    if not fs_addons[in_formspec] then fs_addons[in_formspec] = {} end
    fs_addons[in_formspec][#fs_addons[in_formspec]+1] = {tag=tag, func=func}
end

function aom_inventory.get_formspec_of_type(formspecid, flags)
    flags = flags or {}
    local out = {}
    for i, callbackdef in ipairs(fs_addons[formspecid] or {}) do
        out[#out+1] = callbackdef.func(flags)
    end
    return table.concat(out)
end


aom_inventory.registered_formspec_actions = {}
-- if returns true, blocks other callbacks
local reg_actions = aom_inventory.registered_formspec_actions
function aom_inventory.register_on_formspec_action(formname, fieldname, callback)
    if not reg_actions[formname] then reg_actions[formname] = {} end
    if not reg_actions[formname][fieldname] then reg_actions[formname][fieldname] = {} end
    reg_actions[formname][fieldname] = callback
end

function aom_inventory.on_player_receive_fields(player, formname, fields)
    if reg_actions[formname] then
        for key, val in pairs(fields) do
            if reg_actions[formname][key] then
                if reg_actions[formname][key](player, formname, fields) then return end
            end
        end
    end
    if reg_actions["_any"] then
        for key, val in pairs(fields) do
            if reg_actions["_any"][key] then
                if reg_actions["_any"][key](player, formname, fields) then return end
            end
        end
    end
end

-- gets the context for a node so its formspec is linked to its inventory
function aom_inventory.get_node_formspec_context_pos(pos)
    pos = vector.round(pos)
    return "nodemeta:"..pos.x..","..pos.y..","..pos.z..""
end

minetest.register_on_player_receive_fields(function(player, formname, fields)
    return aom_inventory.on_player_receive_fields(player, formname, fields)
end)
