hades_ghostinv = {}

local inventories = {}
local inventories_detached = {}

hades_ghostinv.declare_inventory = function(name, detached_list)
	if detached_list then
		table.insert(inventories_detached, {name=name, listname=detached_list})
	else
		table.insert(inventories, {name=name})
	end
end

local ghostify_or_unghostify_inventories = function(player, ghost_prefix, unghostify)
	local inv = player:get_inventory()
	local pname = player:get_player_name()
	for i=1, #inventories do
		local list = inventories[i].name
		if not unghostify then
			inv:set_size(ghost_prefix.."_"..list, inv:get_size(list))
		end
		for s=1, inv:get_size(list) do
			local stack
			if not unghostify then
				stack = inv:get_stack(list, s)
				inv:set_stack(ghost_prefix.."_"..list, s, stack)
				inv:set_stack(list, s, "")
			else
				stack = inv:get_stack(ghost_prefix.."_"..list, s)
				inv:set_stack(list, s, stack)
			end
		end
		if unghostify then
			inv:set_size(ghost_prefix.."_"..list, 0)
		end
	end
	for i=1, #inventories_detached do
		local invname = inventories_detached[i].name
		local listname = inventories_detached[i].name
		local dinv = minetest.get_inventory({type="detached", name=pname.."_"..invname})
		if dinv then
			if not unghostify then
				dinv:set_size(ghost_prefix.."_"..listname, dinv:get_size(listname))
			end
			for s=1, dinv:get_size(listname) do
				local stack
				if not unghostify then
					stack = dinv:get_stack(listname, s)
					dinv:set_stack(ghost_prefix.."_"..listname, s, stack)
					dinv:set_stack(listname, s, "")
				else
					stack = dinv:get_stack(ghost_prefix.."_"..listname, s)
					dinv:set_stack(listname, s, stack)
				end
			end
			if unghostify then
				dinv:set_size(ghost_prefix.."_"..listname, 0)
			end
		end
	end
end

hades_ghostinv.ghostify_inventories = function(player, ghost_prefix)
	ghostify_or_unghostify_inventories(player, ghost_prefix, false)
end

hades_ghostinv.unghostify_inventories = function(player, ghost_prefix)
	ghostify_or_unghostify_inventories(player, ghost_prefix, true)
end

hades_ghostinv.declare_inventory("main")
hades_ghostinv.declare_inventory("craft")

