-- Redéfinition de la propriété digiline pour le player_detector
local GET_COMMAND = "GET"
local function object_detector_make_formspec(pos)
	local meta = minetest.get_meta(pos)
	meta:set_string("formspec", "size[9,2.5]" ..
		"field[0.3,  0;9,2;scanname;Name of player to scan for (empty for any):;${scanname}]"..
		"field[0.3,1.5;4,2;digiline_channel;Digiline Channel (optional):;${digiline_channel}]"..
		"button_exit[7,0.75;2,3;;Save]")
end

local object_detector_digiline = {
	receptor = {},
	effector = {
		action = function(pos, node, channel, msg)
			local meta = minetest.get_meta(pos)
			if channel == meta:get_string("digiline_channel") then
				if msg == GET_COMMAND then
					local objs = minetest.get_objects_inside_radius(pos, mesecon.setting("detector_radius", 6))
					
					-- abort if no scan results were found
					if next(objs) == nil then return false end
					
					local scanname = meta:get_string("scanname")
					local scan_for = {}
					for _, str in pairs(string.split(scanname:gsub(" ", ""), ",")) do
						scan_for[str] = true
					end
					local every_player = scanname == ""
					for _, obj in pairs(objs) do
						-- "" is returned if it is not a player; "" ~= nil; so only handle objects with foundname ~= ""
						local foundname = obj:get_player_name()
						if foundname ~= "" then
							if every_player or scan_for[foundname] then
								digilines.receptor_send(pos, digilines.rules.default, channel, foundname)
								break;
							end
						end
					end
					
				else
					meta:set_string("scanname", msg)
					object_detector_make_formspec(pos)
				end
			end
		end
	},
}

minetest.override_item(
	"mesecons_detector:object_detector_off",
	{
		digiline = object_detector_digiline
	})
minetest.override_item(
	"mesecons_detector:object_detector_on",
	{
		digiline = object_detector_digiline
	})

minetest.log("action", "[nalc_mesecons] loaded.")
