local random = math.random
local sound_play = minetest.sound_play
local vector_normalize = vector.normalize
local vector_multiply = vector.multiply
local vector_add = vector.add

weapon_api.lib = {}

--TODO use status effect for cooldown so you can't fly as high
function weapon_api.lib.dash(player, direction, strength)
	player:set_pos(player:get_pos())
	direction = vector_normalize(direction)
	direction = vector_multiply(direction, strength)
	
	local playervel = player:get_player_velocity()
	playervel = vector_add(direction, playervel)
	
	if true or playervel.x * playervel.y * playervel.z < 30
	then
		player:add_player_velocity(direction)
	end
end

weapon_api.lib.proc_on_use = dofile(minetest.get_modpath("weapon_api") .. "/proc.lua")





function weapon_api.lib.default_on_use(itemstack, user, pointed_thing)
	local dir = user:get_look_dir()

	if pointed_thing.type == "object"
	then
		local toolcaps = itemstack:get_tool_capabilities()
		local obj = pointed_thing.ref
		obj:punch(
			user,
			1,
			toolcaps,
			dir)
	end
	
	local def = itemstack:get_definition()
	user:add_player_velocity(vector.multiply(dir, def._weight))
	
	sound_play("weapon_api_woosh", {object = user, pitch = 1 + (random() - 0.5)})
end


function weapon_api.lib.wear_out(itemstack, user)
	local wear = itemstack:get_wear()
	wear = wear + 0x40 --1020 uses
	
	--numbers with prefix 0x are in hexadecimal if you didn't know
	if wear < 0xFFFF
	then
		itemstack:set_wear(wear)
		return itemstack
	else
		minetest.sound_play(generic_media.tool_breaks_default(), {object = user})
		return ItemStack(itemstack:get_name() .. "_broken")
	end
end

function weapon_api.lib.slash(slasher, itemstack, hit_method, range)
	if not slasher
	then
		return
	end
	
	local props = slasher:get_properties()
	
	
	local pos = slasher:get_pos()
	pos.y = pos.y + props.eye_height
	local lookdir = slasher:get_look_dir()
	
	local tippos = vector.add(pos, vector.multiply(lookdir, range))
	
	
	
	local raycast = minetest.raycast(pos, tippos, true, false)
	
	for pointed_thing in raycast
	do
		if pointed_thing.type == "node"
		then
			break
		end
		if pointed_thing.type == "object"
		then
			local obj = pointed_thing.ref
			if not obj:is_player()
			then
				hit_method(slasher, itemstack, obj)
			end
		end
	end
	
end
