
pmb_cooking.recipes = {}


function pmb_cooking.register_cooking(recipe)
    if not pmb_cooking.recipes[recipe.raw] then
        pmb_cooking.recipes[recipe.raw] = {}
    end
    -- prevent improper recipe defs
    if type(recipe.groups) ~= "table" then
        recipe.groups = {[0] = recipe.groups}
    end

    -- add a recipe for each group
    for i, group in pairs(recipe.groups) do
        pmb_cooking.recipes[recipe.raw][group] = {}
        local r = pmb_cooking.recipes[recipe.raw][group]

        r.cooked = recipe.cooked
        r.raw = recipe.raw
        r.output_count = recipe.output_count or 1
        r.input_count = recipe.input_count or 1
        r.cook_time = recipe.cook_time or 5
    end
end

-- example
pmb_cooking.register_cooking({
    raw = "my_input",
    cooked = "my_output",
    input_count = 1, -- optional or 1
    output_count = 1, -- optional or 1
    cook_time = 5, -- optional or 5, how long it takes to cook (if not instant). -1 for instant.
    groups = {"my_cook_type"},
})


function pmb_cooking.get_recipe(name, group)
    if pmb_cooking.recipes[name] then
        return pmb_cooking.recipes[name][group]
    else
        return nil
    end
end


function pmb_cooking.cook(itemstack, group, count)
    local recipe = pmb_cooking.get_recipe(itemstack:get_name(), group)
    if not recipe then return itemstack, nil end
    local maxcount = math.floor(itemstack:get_count() / math.max(recipe.input_count, 1))
    if not count then count = 1
    elseif count > maxcount or count == -1 then count = maxcount end

    local output = ItemStack(recipe.cooked)
    output:set_count(recipe.output_count * count)

    itemstack:take_item(recipe.input_count * count)
    -- minetest.log("cooked name is "..output:get_name())
    return itemstack, output
end


function pmb_cooking.update_infotext(pos)
    local r = ""
    local meta = minetest.get_meta(pos)
    local inv = meta:get_inventory()

    local instack = inv:get_stack("input", 1)
    r = r .. "  in: " .. instack:get_count() .. " " .. instack:get_name()
    r = r .. "\n"

    local outstack = inv:get_stack("output", 1)
    r = r .. "out: " .. outstack:get_count() .. " " .. outstack:get_name()

    meta:set_string("infotext", r)
    return r
end

