local NAME = minetest.get_current_modname()

local formspec =
	"size[6,1]" ..
	"real_coordinates[true]" ..
	"textarea[0,0;5,1;name;Name;]" ..
	"button_exit[5,0;1,1;confirm;Confirm]" ..
	"bgcolor[#FC05E344;false]"

local player_pointed_pos = {}

minetest.register_craftitem(NAME .. ":nametag", {
	description = "Nametag",
	inventory_image = NAME .. "_nametag.png",
	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 name = placer:get_player_name()
			player_pointed_pos[name] = pointed_thing.under
			minetest.show_formspec(name, NAME .. ":nametag", formspec)
		end
		return itemstack
	end
})

minetest.register_on_player_receive_fields(function(player, form, fields)
	if form ~= NAME .. ":nametag" then
		return false
	end

	local position = player_pointed_pos[player:get_player_name()]
		
	if position and fields.name then
		local meta = minetest.get_meta(position)
		meta:set_string("infotext", fields.name)
		local stack = player:get_wielded_item()
		stack:set_count(stack:get_count() -1)
		player:set_wielded_item(stack)
		return true
	end

end)


minetest.register_craft({ --TODO [crafting]
	type = "shapeless",
	output = NAME .. ":nametag",
	recipe = {
		"farming:string", "default:paper"
	}
})
