PyuTest.WIRECUTTER_META_NAME = "WIRECUTTER_TARGET"

local function wirecutter_meta(pos)
	return core.serialize({
		x = pos.x,
		y = pos.y,
		z = pos.z
	})
end

PyuTest.get_node_electricity_targets = function(pos)
	local meta = core.get_meta(pos)
	local s = meta:get_string(PyuTest.WIRECUTTER_META_NAME)

	if s ~= "" then
		local positions = core.deserialize(s)
		local r = {}

		for _, v in pairs(positions) do
			table.insert(r, v)
		end
		return r
	end

	return nil
end

local wirecutter_desc = [[Wirecutter
Left-click to set target
Right-click to bind target to a button or another source]]

PyuTest.make_item("pyutest_electricity:wirecutter", wirecutter_desc, {
	electric = 1,
	tool = 1
}, "pyutest-wirecutter.png", {
	stack_max = 1,

	on_use = function (itemstack, user, pointed_thing)
		if pointed_thing.type == "node" then
			local s = wirecutter_meta(pointed_thing.under)
			itemstack:get_meta():set_string(PyuTest.WIRECUTTER_META_NAME, s)
		end
		return itemstack
	end,

	on_place = function (itemstack, placer, pointed_thing)
		local s = itemstack:get_meta():get_string(PyuTest.WIRECUTTER_META_NAME)

		if s ~= "" then
			local pos = pointed_thing.under
			local pos2 = core.deserialize(s)
			itemstack:get_meta():set_string(PyuTest.WIRECUTTER_META_NAME, "")

			local meta = core.get_meta(pos)
			local oldvalue = core.deserialize(meta:get_string(PyuTest.WIRECUTTER_META_NAME))
			if oldvalue ~= nil then
				oldvalue[string.format("%f,%f,%f", pos2.x, pos2.y, pos2.z)] = pos2
				meta:set_string(PyuTest.WIRECUTTER_META_NAME, core.serialize(oldvalue))
			else
				core.chat_send_player(placer:get_player_name(), "Failed.")
			end
		else
			core.chat_send_player(placer:get_player_name(), "No target set.")
		end

		return itemstack
	end
})

core.register_craft({
	output = "pyutest_electricity:wirecutter",
	recipe = {
		"pyutest_ores:copper_ingot",
		"pyutest_ores:copper_ingot",
	},
	type = "shapeless"
})
