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

local function get_default_kit()
    return {
        priv = "",
        items = {},
    }
end

function aom_kits.add_to_kit(kitname, item_list)
    if not aom_kits.k[kitname] then aom_kits.k[kitname] = get_default_kit() end
    table.insert_all(aom_kits.k[kitname].items, item_list)
end

function aom_kits.give_kit(player, kitname)
    local kit = aom_kits.k[kitname]
    if not kit then return false end
    local inv = player:get_inventory()
    local pos = player:get_pos()
    for _, item in pairs(kit.items) do
        local stack = ItemStack(item)
        stack = inv:add_item("main", stack)
        if stack:get_count() > 0 then
            minetest.add_item(pos, stack)
        end
    end
end

minetest.register_privilege("aom_kits", {
    description = S("Allows a player to give themselves a kit"),
    give_to_singleplayer = false
})

minetest.register_chatcommand("kit", {
    params = "(give [kit name] (player name))",
    description = S("Gives kits"),
    privs = {aom_kits = true},
    func = function(name, param)
        local player = minetest.get_player_by_name(name)
        local parse = string.split(param, " ")
        if (parse[1] == "give") then
            local kitname = parse[2]
            if parse[3] then
                if minetest.get_player_by_name(parse[3]) then
                    name = parse[3]
                else
                    return false, S("Error: no player with name "..parse[3])
                end
            end
            if not aom_kits.k[kitname] then
                return false, S("Error: no kit with name "..kitname)
            end

            aom_kits.give_kit(minetest.get_player_by_name(name), kitname)
            return true, S("Kit "..kitname.." given to "..name)
        end
        return false, S("Error: Invalid")
    end
})
