-- support for MT game translation.
local S = minetest.get_translator("fire")

local function strike_fire(user, pointed_thing)
	-- Play sound
	local sound_pos = pointed_thing.above or user:get_pos()
	minetest.sound_play("fire_flint_and_steel",
		{pos = sound_pos, gain = 0.1, max_hear_distance = 8}, true)
	-- Fire privilege
	local name = user:get_player_name()
	if not minetest.get_player_privs(name)["fire"] then
		minetest.chat_send_player(name, S("You need the 'fire' privilege."))
		return
	end
	-- Use tinder, place flame
	if pointed_thing.type == "node" then
		local node_under = minetest.get_node(pointed_thing.under).name
		local nodedef = minetest.registered_nodes[node_under]
		if not nodedef then
			return
		end
		if minetest.is_protected(pointed_thing.under, name) then
			minetest.record_protection_violation(pointed_thing.under, name)
			return
		end
		local inv = user:get_inventory()
		if not inv:contains_item("main", "fire:tinder") then
			minetest.chat_send_player(name, S("You need tinder to ignite the striker!"))
			return
		end

		if nodedef.on_ignite then
			nodedef.on_ignite(pointed_thing.under, user)
		elseif minetest.get_item_group(node_under, "flammable") >= 1
				and minetest.get_node(pointed_thing.above).name == "air" then
			if minetest.is_protected(pointed_thing.above, name) then
				minetest.record_protection_violation(pointed_thing.above, name)
				return
			end

			minetest.set_node(pointed_thing.above, {name = "fire:basic_flame"})
		else
			return
		end

		if not minetest.is_creative_enabled(name) then
			inv:remove_item("main", "fire:tinder")
		end
		return true
	end
end

minetest.register_craftitem("fire:tinder", {
	description = S("Tinder"),
	inventory_image = "flint_tinder.png",
})

minetest.register_tool("fire:flint_and_steel", {
	description = S("Fire Striker"),
	_tt_help = S("Requires tinder to ignite"),
	inventory_image = "flint_firestriker.png",
	range = 2.5,
	on_place = function(itemstack, user, pointed_thing)
		if strike_fire(user, pointed_thing) then
			if not minetest.is_creative_enabled(user) then
				-- Wear tool
				local wdef = itemstack:get_definition()
				itemstack:add_wear_by_uses(15)

				-- Tool break sound
				local sound_pos = pointed_thing.above or user:get_pos()
				if itemstack:get_count() == 0 and wdef.sound and wdef.sound.breaks then
					minetest.sound_play(wdef.sound.breaks,
						{pos = sound_pos, gain = 0.5}, true)
				end
				return itemstack
			end
		end
		return itemstack
	end
})

--
-- Craft
--

minetest.register_craft({
	output = 'fire:flint_and_steel',
	recipe = {
		{'default:flint', 'default:steel_ingot'},
	}
})

minetest.register_craft({
	output = 'fire:tinder',
	recipe = {
		{'farming:cotton'},
	}
})

minetest.register_craft({
	output = 'fire:tinder',
	recipe = {
		{'farming:wheat'},
	}
})

minetest.register_craft({
	output = 'fire:tinder',
	recipe = {
		{'default:paper'},
	}
})
