-- LUALOCALS < ---------------------------------------------------------
local minetest, nodecore, pairs, vector
    = minetest, nodecore, pairs, vector
-- LUALOCALS > ---------------------------------------------------------

nodecore.register_limited_abm({
		label = "Lux Reaction",
		interval = 1,
		chance = 2,
		limited_max = 100,
		nodenames = {"group:lux_cobble"},
		action = function(pos, node)
			local qty = nodecore.lux_react_qty(pos)
			local name = node.name:gsub("cobble%d", "cobble" .. qty)
			if name == node.name then return end
			minetest.set_node(pos, {name = name})
		end
	})

nodecore.register_aism({
		label = "Lux Stack Reaction",
		interval = 1,
		chance = 2,
		itemnames = {"group:lux_cobble"},
		action = function(stack, data)
			local name = stack:get_name()
			if minetest.get_item_group(name, "lux_cobble") <= 0 then return end
			local qty = nodecore.lux_react_qty(data.pos)
			name = name:gsub("cobble%d", "cobble" .. qty)
			if name == stack:get_name() then return end
			stack:set_name(name)
			return stack
		end
	})

local function playercheck(player)
	local found
	local stacks = {}
	local inv = player:get_inventory()
	for i = 1, inv:get_size("main") do
		local stack = inv:get_stack("main", i)
		if minetest.get_item_group(stack:get_name(), "lux_cobble") > 0 then
			stacks[i] = stack
			found = true
		end
	end
	if not found then return end
	local qty = nodecore.lux_react_qty(vector.add(player:get_pos(), {x = 0, y = 1, z = 0}))
	for k, v in pairs(stacks) do
		local name = v:get_name()
		local nn = name:gsub("cobble%d", "cobble" .. qty)
		if name ~= nn then
			v:set_name(nn)
			inv:set_stack("main", k, v)
		end
	end
end
local function playercheckall()
	minetest.after(1, playercheckall)
	for _, p in pairs(minetest.get_connected_players()) do
		playercheck(p)
	end
end
playercheckall()
