local get_node_or_nil = minetest.get_node_or_nil
local reg_nodes = minetest.registered_nodes
local add_node = minetest.add_node
local sound_play = minetest.sound_play

local S = minetest.get_translator("degradable_walls")

local function place_as_pillar(itemstack, user, pointed_thing)
	if pointed_thing.type == "node"
	then
		local name = itemstack:get_name()
		local place_sound = reg_nodes[name].sounds.place
		local height = itemstack:get_count()
		if height > 5 then height = 5 end
		
		
		local pos = vector.new(pointed_thing.above)
		for i = 1, height
		do
			local node = get_node_or_nil(pos)
			if node and (reg_nodes[node.name] or {}).buildable_to
			then
				sound_play(place_sound)
				add_node(pos, {name = name})
				pos.y = pos.y + 1
			else
				itemstack:take_item(i - 1)
				return itemstack
			end
		end
		
		itemstack:take_item(height)
		return itemstack
	end
end






minetest.register_node("degradable_walls:wall",
	{
		description = S("Reinforced Wall"),
		tiles = {"degradable_walls_wall.png"},
		groups = {cracky = 1, stone = 1},
		on_use = place_as_pillar,
		sounds = generic_media.node_sound_stone_defaults(),
		stack_max = 128,
	})
minetest.register_alias("wall", "degradable_walls:wall")



crafting.register_recipe(
	{
		output = "wall 8",
		type = "inv",
		items = {"cobble", "mortar"},
		always_known = "true",
	})

local erosion_order = {"wall"}
local repairable_hashtable = {}
for i = 1, 5
do
	local name = "degradable_walls:cracked_wall_" .. i
	local description = "Cracked Wall"
	for ii = 2, i
	do
		description = "Very " .. description
	end
	local crackiness
	if i > 3
	then
		crackiness = 3
	else
		crackiness = i
	end
	
	minetest.register_node(name, {
		description = S(description),
		tiles = {"degradable_walls_wall.png^[crack:1:" .. i},
		is_ground_content = false,
		groups = {cracky = crackiness, stone = 1, not_in_creative_inventory = 1},
		sounds = generic_media.node_sound_stone_defaults(),
		on_use = place_as_pillar,
		stack_max = 128,
	})
	repairable_hashtable[minetest.get_content_id(name)] = true
	erosion_order[i + 1] = name
end

minetest.register_node("degradable_walls:debris",
	{
		description = S("Debris"),
		tiles = {"basic_ground_nodes_rubble.png"},
		is_ground_content = false,
		groups = {crumbly = 3, falling_node = 1},
		sounds = generic_media.node_sound_gravel_defaults(),
		drop =
		{
			max_items = 1,
			items =
			{
				{
					rarity = 3,
					items = {"cobble"}
				}
			}
		}
	})
minetest.register_alias("debris", "degradable_walls:debris")

erosion_order[7] = "debris"
erosion_order[8] = "air"
erosion.register_erosion({"cobble", "debris"})
erosion.register_erosion(erosion_order)

give_initial_stuff.add("wall 128")

dofile(minetest.get_modpath("degradable_walls") .. "/mortar.lua")(repairable_hashtable)


