
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 = {}


local modpath = minetest.get_modpath("weapon_api")

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

	if pointed_thing.type == "object" and not minetest.is_player(pointed_thing.ref)
	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


local function 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










weapon_api.lib = {}

--TODO use status effect for cooldown so you can't fly as high
function weapon_api.lib.dash(player, direction, strength)
	direction = vector_normalize(direction)
	direction = vector_multiply(direction, strength)

	local playervel = player:get_player_velocity()
	playervel = vector_add(direction, playervel)

	if playervel.x * playervel.y * playervel.z < 30
	then
		player:add_player_velocity(direction)
	end
end
















local proc_on_use = dofile(modpath .. "/proc.lua")








local prototype =
{
	tool_capabilities =
	{
		full_punch_interval = 0,
		max_drop_level = 0,
		damage_groups =
		{
			fleshy = 4,
		},
	},
	on_use = default_on_use,
	stack_max = 1,
	_weight = 3,
	on_drop = function() end,
	after_use = wear_out,
}



function weapon_api.register_weapon(name, def)
	local copy = {}
	for k, v in pairs(prototype)
	do
		copy[k] = v
	end
	for k, v in pairs(def)
	do
		copy[k] = v
	end
	if copy._proc
	then
		copy._proc = nil
		copy.on_use = proc_on_use
	end
	minetest.register_tool(name, copy)
end
