local mod_name = core.get_current_modname()
local mod_path = core.get_modpath(mod_name)
local S = core.get_translator(mod_name)

aom_igm.registered_pages = {}
aom_igm.registered_page_actions = {}


-- if returns false, cancels as if not allowed to show this
-- callback(player, pagename, fs_table) --> false or nil
function aom_igm.register_page_process(pagename, callback, data)
    if not aom_igm.registered_pages[pagename] then aom_igm.registered_pages[pagename] = {} end
    table.insert(aom_igm.registered_pages[pagename], callback)
end

-- returns false if not allowed to show this formspec
function aom_igm.get_formspec(player, pagename)
    local calls = aom_igm.registered_pages[pagename]
    if not calls then return false end
    local fs = {}
    local data = {}
    for i, callback in ipairs(calls) do
        local ret = callback(fs, player, pagename, data)
        if ret == false then return false end
    end
    return table.concat(fs, "")
end

-- interactions
core.register_on_player_receive_fields(function(player, formname, fields)
    if formname:sub(1,7) ~= "aom_igm" then return end
    local pagename = formname:split(":")[2] or ""
    local callbacks = aom_igm.registered_page_actions[pagename]
    if not callbacks then return end
    -- core.log(pagename)
    for i, callback in ipairs(callbacks) do
        callback(player, pagename, fields)
    end
end)

-- set up internal stuff
aom_igm.register_page_process("main", function(fs, player, pagename, data)
    table.insert(fs, "")
end)

-- callback(player, pagename, fields)
function aom_igm.register_page_action(pagename, callback)
    if not aom_igm.registered_page_actions[pagename] then aom_igm.registered_page_actions[pagename] = {} end
    table.insert(aom_igm.registered_page_actions[pagename], callback)
end


function aom_igm.show_page(player, pagename)
    local fs = aom_igm.get_formspec(player, pagename)
    if not fs then return false end
    core.show_formspec(player:get_player_name(), "aom_igm:" .. pagename, fs)
    return true
end


core.register_chatcommand("menu", {
    params = "",
    description = S("Opens the in game menu with aom_igm"),
    privs = {},
    func = function(name, param)
        local player = core.get_player_by_name(name)
        if not aom_igm.show_page(player, "main") then
            return false, S("Not allowed to view that page, or page doesn't exist.")
        end
        return true
    end
})






