local NAME = minetest.get_current_modname()

minetest.register_tool(NAME .. ":cableinserter", {
	description = "Cable Inserter",
	inventory_image = "cableinserter.png",
	stack_max = 1,
	on_place = function(itemstack, placer, pointed_thing)
		-- TODO Check that nodes does not already interact with the grid
		if pointed_thing["type"] == "node" then
			local node = minetest.get_node(pointed_thing.under)
			local meta = minetest.get_meta(pointed_thing.under)
			local inv = placer:get_inventory()
			local s = ItemStack("sparkcore:cable")
			s:set_count(1)

			if meta:get_int("sparktech_net_passive") == 1 then
				meta:set_int("sparktech_net_passive", 0)
				sparktech.remove_node_from_net(pointed_thing.under, node, true)
				notify.hud.sendtext(placer:get_player_name(), "Cable Inserter: Removed cable")
				if inv:room_for_item("main", s) then
					inv:add_item("main", s)
				else
					minetest.item_drop(s, placer, pointed_thing.above)
				end
			else
				if inv:remove_item("main", s):get_count() ~= 0 then
					meta:set_int("sparktech_net_passive", 1)
					sparktech.add_node_to_net(pointed_thing.under, node)
					notify.hud.sendtext(placer:get_player_name(), "Cable Inserter: Added cable", 5)
				end
			end
		end
		return itemstack
	end,
	on_use = function(itemstack, user, pointed_thing)
		if pointed_thing["type"] == "node" then
			local node = minetest.get_node(pointed_thing.under)
			local meta = minetest.get_meta(pointed_thing.under)
			if meta:get_int("sparktech_net_passive") == 1 then
				notify.hud.sendtext(user:get_player_name(), "Cable Inserter: Contains cable")
			else
				notify.hud.sendtext(user:get_player_name(), "Cable Inserter: Does not contain a cable")
			end
		end
	end
})

minetest.register_craft({
	output = NAME .. ":cableinserter",
	recipe = {
		{ "orioncraft:iron_bar", "", "" },
		{ "", "orioncraft:iron_bar", "" },
		{ "", "orioncraft:iron_bar", ""},
	}
})
