local S = minetest.get_translator("repairing_anvils")


local recipes = repairing_anvils.recipes

local function forge(itemstack, user)

	local name = string.split(itemstack:to_string(), " ")
	local recipe = recipes[name[1]]

	if recipe
	then
		local did_something = false
		if type(recipe) == "string"
		then
			minetest.sound_play("repairing_anvils_strikes", {pos = pos})
			local i = itemstack:take_item()
			if not i:is_empty()
			then
				if itemstack:is_empty()
				then
					itemstack:add_item(recipe)
					return ItemStack(nil)
				else
					return ItemStack(recipe)
				end
			end
		else
			return recipe(itemstack)
		end

	end
end

local function anvil_rightclick(pos, node, clicker, itemstack)
	local inv = clicker:get_inventory()

	local stackcopy = itemstack:peek_item(itemstack:get_count())
	local workpiece = forge(stackcopy, clicker)
	if workpiece
	then
		if inv:room_for_item("main", workpiece)
		then
			inv:add_item("main", workpiece)
			itemstack = stackcopy
		end
	end
	return itemstack
end

local tooltip = S("Anvil\n@1",
	minetest.colorize("#90FFFF", S("Used to repair tools")))

local function anvil_set_infotext(pos)
	local meta = minetest.get_meta(pos)
	meta:set_string("infotext", tooltip)
end


minetest.register_node("repairing_anvils:anvil",
	{
		description = tooltip,
		drawtype = "mesh",
		mesh = "repairing_anvils_anvil.obj",
		tiles = {"repairing_anvils_anvil.png"},
		groups = {cracky = 1, falling_node = 1},
		sounds = generic_media.node_sound_metal_defaults(),
		paramtype2 = "facedir",
		on_rightclick = anvil_rightclick,
		stack_max = 1,
		collision_box =
		{
			type = "fixed",
			fixed = {
				{-0.5, -0.5, -1/4, 0.5, 0.5, 1/4},
			},
		},
		selection_box =
		{
			type = "fixed",
			fixed = {
				{-0.5, -0.5, -1/4, 0.5, 0.5, 1/4},
			},
		},
		on_construct = anvil_set_infotext
	})
minetest.register_alias("anvil", "repairing_anvils:anvil")

crafting.register_recipe(
	{
		output = "anvil",
		type = "inv",
		items = {"iron_ingot 8"},
		always_known = true,
	})
--https://freesound.org/people/alan3809/sounds/103071/
