----------------------------------------------------------------
--
-- To add a menu to an object (such as a Brick Oven), you will
-- be adding a function 'lookmenu' to the appropriate class,
-- like this:
--
-- function brickoven.lookmenu(add)
--    add("Light Oven", function () ... end)
--    add("Add Fuel", function () ... end)
-- end
--
-- This function will get called twice: once in a 'probe' when
-- Unreal wants to know what menu items exist, and a second time
-- in an 'invoke' to find the right closure.  The 'add' function
-- which is passed in can therefore be one of two functions.
--
-- In probe mode, the goal is to build up an array that looks
-- like this:
--
--   {"Light Oven", "Add Fuel"}
--
-- So therefore, in probe mode, the 'add' function is a closure
-- that adds the label to the array.
--
-- In invoke mode, the goal is to find the right closure.  So
-- therefore, in invoke mode, the 'add' function is a closure
-- that compares the label to the menu item which was already
-- selected.  If there's a match, it records the closure.
--
----------------------------------------------------------------

makeclass('probe')
makeclass('invoke')

function probe.getmenu()
    local class = tangible.getclass(place)

    -- if the tangible doesn't have a 'lookmenu' function, do nothing
    if class == nil or class.lookmenu == nil then
        return {}
    end

    local items = {}
    local add = function(label, closure)
        table.insert(items, label)
    end
    class.lookmenu(add)
    return items
end

function invoke.pressmenu(label)
    local class = tangible.getclass(place)

    -- if the tangible doesn't have a 'lookmenu' function, do nothing
    if class == nil or class.lookmenu == nil then
        return
    end

    local menuclosure = nil
    local add = function(lbl, closure)
        if (lbl == label) then
            menuclosure = closure
        end
    end
    class.lookmenu(add)
    if menuclosure ~= nil then
        menuclosure()
    end
end
