
local vector_multiply = vector.multiply

local vector_length = vector.length
local sound_play = minetest.sound_play
local random = math.random
local dash = weapon_api.lib.dash




local PROC_DURATION = 1
local PROC_DASH = 5

local proc_effect
do
	local particledef =
	{
		amount = 50,
		time = 0.1,
		minvel = {x = -10, y = -10, z = -10},
		maxvel = {x = 10, y = 10, z = 10},
		minexptime = 0.5,
		maxexptime = 1,
		minsize = 1,
		maxsize = 5,
		texture = "weapon_api_rampage_particle.png",
		glow = 14,
		animation =
		{
			type = "vertical_frames",
			aspect_w = 16,
			aspect_h = 16,
			length = 0.5,
		}

	}
	local meta =
	{
		__call = function(self, pos)
			self.minpos = pos
			self.maxpos = pos
			return self
		end
	}
	setmetatable(particledef, meta)


	proc_effect = function(pos, hit)
		minetest.add_particlespawner(particledef(pos))
		if hit
		then
			minetest.sound_play(
				"weapon_api_proc",
				{
					pos = pos,
					max_hear_distance = 8,
					gain = 0.5,
					pitch = 1 + (random() - 0.5) / 2
				})
			else
				minetest.sound_play(
					"weapon_api_proc",
					{
						pos = pos,
						max_hear_distance = 8,
						gain = 0.02,
						pitch = 1 - (random() / 2)
					})
			end
	end

end


local proc_status_effect = status_effects.StatusEffect(
	{
		name = "proc",
	})
local function proc_on_use(itemstack, user, pointed_thing)
	local dir = user:get_look_dir()
	local dead
	local dash_multiplier = 1
	local name = user:get_player_name()
	local proc = proc_status_effect.player_has(name)
	if pointed_thing.type == "object"
	then
		local toolcaps = itemstack:get_tool_capabilities()
		local obj = pointed_thing.ref
		if proc
		then
			local luae = obj:get_luaentity()
			if luae.die
			then
				luae:die()
			end
		end
		obj:punch(
			user,
			1,
			toolcaps,
			dir)

		if obj:get_luaentity().dead
		then
			dash_multiplier = PROC_DASH
			proc_status_effect.give_to(name, PROC_DURATION)
			proc_effect(obj:get_pos(), true)
		end
	elseif proc
	then
		dash_multiplier = PROC_DASH
		proc_effect(user:get_pos())
	end



	local def = itemstack:get_definition()
	dash(user, dir, def._weight * dash_multiplier)


	sound_play("weapon_api_woosh", {object = user, pitch = 1 + (random() - 0.5)})
end


--fall damage immunity during proc
minetest.register_on_player_hpchange(
	function(player, hp_change, reason)
		if reason.type == "fall"
		then
			if proc_status_effect.player_has(player:get_player_name())
			then
				return 0
			end
		end
		return hp_change
	end, true)



return proc_on_use
