vg_legacy = {}

local log = voxelgarden.get_logger()
vg_legacy.registered_item_conversions = {}

function vg_legacy.convert_itemstack(itemstack)
	local new = vg_legacy.registered_item_conversions[itemstack:get_name()]
	if not new then return end

	if type(new) == "string" then
		itemstack:set_name(new)
	elseif type(new) == "function" then
		new(itemstack)
	end
end

function vg_legacy.convert_inventory(inv)
	local lists = inv:get_lists()
	for _, list in pairs(lists) do
		for _, itemstack in ipairs(list) do
			vg_legacy.convert_itemstack(itemstack)
		end
	end
	inv:set_lists(lists)
end

-- "old" -> "new" / "old" -> new(itemstack)
function voxelgarden.register_item_conversion(old, new)
	log:assert(type(old) == "string", "Invalid old itemstring passed to register_item_conversion")
	log:assert(type(new) == "string" or type(new) == "function", "Invalid new itemstring/callback passed to " ..
		"register_item_conversion")
	if not vg_legacy.registered_item_conversions[old] then
		vg_legacy.registered_item_conversions[old] = new
	end
end

core.register_on_joinplayer(function(player)
	vg_legacy.convert_inventory(player:get_inventory())
end)

core.register_lbm({
	label = "Inventory conversion",
	name = "vg_legacy:inv_conversion",
	nodenames = {"group:container"},
	run_at_every_load = true,
	action = function(pos, node)
		local meta = minetest.get_meta(pos)
		vg_legacy.convert_inventory(meta:get_inventory())
	end
})
