local function dropper_formspec(pos)
	local spos = string.format("%d,%d,%d", pos.x, pos.y, pos.z)

	return table.concat({
		"size[8,9]",
		"list[nodemeta:", spos, ";main;0,0;8,4;]",
		"list[context;items;2.5,1;3,3;]",
		"list[current_player;main;0,5;8,4;]"
	})
end

PyuTest.make_electricity_device("pyutest_electricity:dropper", "Dropper", {
	cracky = PyuTest.BLOCK_NORMAL
}, {
	"pyutest-dropper.png",
}, nil, {
	on_construct = function (pos)
		local meta = core.get_meta(pos)
		local inventory = meta:get_inventory()
		inventory:set_size("items", 3 * 3)
		meta:set_string("formspec", dropper_formspec(pos))
	end,
	on_destruct = function(pos)
		local drops = {}
		PyuTest.get_inventory_drops(pos, "items", drops)

		for _, v in pairs(drops) do
			core.add_item(pos, v)
		end
	end,
	_pyutest_blast_resistance = 3
}, function (pos, node, sender_pos)
	local meta = core.get_meta(pos)
	local inv = meta:get_inventory()

	for i = 1, inv:get_size("items") do
		local stack = inv:get_stack("items", i)

		if stack:get_count() > 0 then
			local it = stack:take_item()
			PyuTest.drop_item(pos, it)
			inv:set_stack("items", i, stack)
			break
		end
	end
end)

core.register_craft({
	output = "pyutest_electricity:dropper",
	recipe = {
		{"group:cobble", "group:cobble", "group:cobble"},
		{"group:cobble", "", "group:cobble"},
		{"group:cobble", "pyutest_ores:zinc_ingot", "group:cobble"}
	}
})

local function dispense_stack(pos, itemstack)
	local name = itemstack:get_name()
	local def = core.registered_items[name]

	if def.__on_dispense then
		itemstack = def.__on_dispense(pos, itemstack) or itemstack
	else
		local it = itemstack:take_item()
		PyuTest.drop_item(pos, it)
	end

	return itemstack
end

PyuTest.make_electricity_device("pyutest_electricity:dispenser", "Dispenser", {
	cracky = PyuTest.BLOCK_NORMAL
}, {"pyutest-dispenser.png"}, nil, {
	on_construct = function (pos)
		local meta = core.get_meta(pos)
		local inventory = meta:get_inventory()
		inventory:set_size("items", 3 * 3)
		meta:set_string("formspec", dropper_formspec(pos))
	end,
	on_destruct = function(pos)
		local drops = {}
		PyuTest.get_inventory_drops(pos, "items", drops)

		for _, v in pairs(drops) do
			core.add_item(pos, v)
		end
	end,
	_pyutest_blast_resistance = 3
}, function (pos, node, sender_pos)
	local meta = core.get_meta(pos)
	local inv = meta:get_inventory()

	for i = 1, inv:get_size("items") do
		local stack = inv:get_stack("items", i)

		if stack:get_count() > 0 then
			local it = dispense_stack(pos, stack)
			inv:set_stack("items", i, stack)
			break
		end
	end
end)

core.register_craft({
	output = "pyutest_electricity:dispenser",
	recipe = {
		{"group:cobble", "group:cobble", "group:cobble"},
		{"group:cobble", "pyutest_ores:copper_ingot", "group:cobble"},
		{"group:cobble", "pyutest_ores:zinc_ingot", "group:cobble"}
	}
})
