core.register_privilege("builder", {
	description = "Builder/World Edit Privilege",
	give_to_singeplayer = true
})

core.register_chatcommand("replacenear", {
	params = "<range> <from> <to>",
	description = [[Replace blocks around <range> from <from> to <to>.
	FROM can be comma seperated, or it can be `any` which replaces any node.
	Or it can be `anyblock` which replaces any node other than air and ignore.]],
	privs = {
		builder = true
	},
	func = function(name, param)
		local parts = param:split(" ")
		if #parts == 3 then
			local player = core.get_player_by_name(name)
			local pos = player:get_pos()
			local range = tonumber(parts[1]) or 5
			local from = parts[2]:split(",")
			local to = parts[3]
			local replaced = 0

			local function replace(p)
				for _, v in pairs(from) do
					local nname = core.get_node(p).name
					local anyblock_match = (
						v == "anyblock"
						or v == "anynode"
						and nname ~= "air"
						and nname ~= "ignore"
					)

					if nname == v or v == "any" or anyblock_match then
						core.set_node(p, { name = to })
						replaced = replaced + 1
					end
				end
			end

			PyuTest.dorange(pos, range, function(p)
				replace(p)
			end)

			return true, string.format("Replaced %d blocks", replaced)
		end
		return false, "Requires 3 arguments"
	end
})

core.register_chatcommand("place", {
	params = "<schematic>",
	description = "Place <schematic> at player position",
	privs = {
		builder = true
	},
	func = function(name, param)
		local player = core.get_player_by_name(name)
		core.place_schematic(player:get_pos(),
		PyuTest.get_schematic_path(param),
		"random",
		nil,
		false,
		"place_center_x, place_center_z"
		)
	end
})

core.register_chatcommand("drain", {
	params = "<range>",
	description = "Drain all liquid in <range>",
	privs = {
		builder = true
	},
	func = function(name, param)
		local player = core.get_player_by_name(name)
		local range = tonumber(param) or 1

		PyuTest.dorange(player:get_pos(), range, function(p)
			local node = core.get_node(p)

			if core.get_item_group(node.name, "liquid") ~= 0 then
				core.remove_node(p)
			end
		end)
	end
})
