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


local function checkfix_reg(category, name)
    local cat = aom_scrap._register[category]
    if not cat then
        cat = {}
        aom_scrap._register[category] = cat
    end
    local list = name and cat[name]
    if name and not list then
        list = {}
        cat[name] = list
    end
    return cat, list
end

-- basic general register that allows you to reg anything you want
aom_scrap._register = {}
function aom_scrap.register(category, name, data)
    local cat, list = checkfix_reg(category, name)
    if cat._process ~= nil then
        data = cat._process(name, data) or data
    end
    table.insert(list, data)
end

-- causes registrations to use the callback as well as then storing them
function aom_scrap.register_process(category, callback)
    local cat, list = checkfix_reg(category)
    cat._process = callback
end

function aom_scrap.get_registered(category, tag)
    return (aom_scrap._register[category] and aom_scrap._register[category][tag]) or {}
end

function aom_scrap.scrappify(stack)
    stack = ItemStack(stack)
    local idef = stack:get_definition()
    local ret = {}
    local sourcecount = stack:get_count()

    for iname, icount in pairs(idef._scrap or {}) do
        if icount > 0 then
            local istack = ItemStack(iname)
            istack:set_count(icount * sourcecount)
            if istack:is_known() then -- only use defined items
                local max = istack:get_stack_max() or 1
                local over_limit = istack:get_count() - max
                if over_limit > 0 then istack:set_count(max) end
                table.insert(ret, istack)
                while over_limit > 0 do
                    local overstack = ItemStack(iname)
                    overstack:set_count(math.max(1, math.min(max, over_limit)))
                    table.insert(ret, overstack)
                    over_limit = over_limit - overstack:get_count()
                end
            end
        end
    end
    if #ret == 0 then return nil end
    return ret
end


-- minetest.register_chatcommand("scrap", {
--     params = "",
--     description = S(""),
--     privs = {},
--     func = function(name, param)
--         local stack = ItemStack(param)
--         if stack:is_empty() then return false, "ERROR, invalid itemstack" end
--         local idef = stack:get_definition()
--         local scrapped = aom_scrap.scrappify(stack)
--         minetest.log(dump(scrapped))
--     end
-- })
