local dagger_uses = 16

minetest.register_tool("sorcery:dagger", {
	description = "Sacrificial Dagger",
	inventory_image = "sorcery_dagger.png",
	tool_capabilities = {
		full_punch_interval = 1.6,
		max_drop_level = 1,
		damage_groups = { fleshy = 2 },
	},
	sound = { breaks = "default_tool_breaks" },
	groups = { sorcery_sanctify = 1, sword = 1 },
	punch_attack_uses = 16
})

local dagger_usefn = function(selfharm)
	return function(stack,user,pointat)
		if (not minetest.is_player(pointat)) and
				selfharm == false then
			return nil
		end

		local inv = user:get_inventory()
		local btl = ItemStack('vessels:glass_bottle')
		if not inv:contains_item('main', btl) then
			return nil
		end

		local damage
		local blood
		local target
		if selfharm then
			damage = 3
			blood = ItemStack('sorcery:blood 1')
			target = user
		else
			if not minetest.is_player(pointat) then
				return nil
			end
			damage = 5
			blood = ItemStack('sorcery:blood 3')
			target = pointat
		end
		local pos = target:get_pos()
		pos.y = pos.y + 1.5

		local wear = 65535 / dagger_uses
		stack:add_wear(wear)

		inv:remove_item('main',btl)
		inv:add_item('main',blood)

		target:punch(user, 1.0, {
			full_punch_interval = 1.0,
			damage_groups = { fleshy = damage },
		}, nil)
		for i=0, 48 do
			minetest.add_particle{
				texture = 'sorcery_blood_' .. math.random(5) .. '.png',
				size = 7,
				expirationtime = 2 + math.random(),
				glow = 1,
				pos = pos,
				velocity = {
					x = (math.random() * 3.0) - 1.5,
					y = math.random(),
					z = (math.random() * 3.0) - 1.5
				},
				acceleration = {
					x = 0,
					y = -1,
				 	z = 0
				}
			}
		end

		if math.random(3) == 1 then
			-- we've used up the consecration
			local unholy = ItemStack("sorcery:dagger")
			unholy:set_wear(stack:get_wear())
			return unholy
		else
			-- consecration is holding, return dagger as-is
			return stack
		end
	end
end


minetest.register_tool("sorcery:dagger_consecrated", {
	description = "Consecrated Dagger",
	inventory_image = "sorcery_dagger_consecrated.png",
	tool_capabilities = {
		full_punch_interval = 1.6,
		max_drop_level = 1,
		damage_groups = { fleshy = 6 },
	},
	sound = { breaks = "default_tool_breaks" },
	groups = { sorcery_sanctify = 2, sword = 1 },
	punch_attack_uses = 16,
	on_use = dagger_usefn(false),
	on_secondary_use = dagger_usefn(true),
})
