local mod_name = minetest.get_current_modname()
local mod_path = minetest.get_modpath(mod_name)
local S = minetest.get_translator(mod_name)

local function use_spear(itemstack, user, pointed_thing)
    if pmb_combat.cooldown.can_use(itemstack) then
        itemstack = pmb_combat.cooldown.wear_start(itemstack, "windup")
        minetest.sound_play(("pmb_fenn_spear_draw"), {
            gain = 0.5,
            object = user,
            max_hear_distance = 100,
            pitch = (math.random()*0.1) + 0.90
        })
    end
    return itemstack
end

minetest.register_tool("pmb_fenn:spear", {
    description = S("Fenn Spear"),
    inventory_image = "pmb_fenn_spear_inv.png",
    groups = { not_in_creative_inventory = 1 },
    range = 0,
    on_secondary_use = function(itemstack, user, pointed_thing)
        return pmb_combat.cooldown.attempt_to_use(itemstack, user, pointed_thing)
    end,
    on_place = function(itemstack, user, pointed_thing)
        return pmb_combat.cooldown.attempt_to_use(itemstack, user, pointed_thing)
    end,
    on_select = function(itemstack, player)
    end,
    on_deselect = function(itemstack, player)
        player_model.unset_anim(player, "pmb_fenn_spear_aim")
        return pmb_combat.cooldown.on_wield_change_from(itemstack, player)
    end,
    on_step = function(itemstack, player, dtime)
        local just_thrown = false
        itemstack, just_thrown = pmb_combat.throwable.on_wield_throwable(player, "pmb_fenn:spear_ENTITY", itemstack, {
            allow_partial_throw = true
        })
        if just_thrown then
            wield3d.update(player, {
                _wield3d_textures = "blank.png",
            })
            player_model.unset_anim(player, "pmb_fenn_spear_aim")
            minetest.sound_play(("pmb_fenn_spear_throw"), {
                gain = 0.9,
                object = player,
                max_hear_distance = 50,
                pitch = (math.random()*0.1) + 0.90
            })
        end
        return itemstack
    end,

    _on_cooldown_complete = function(itemstack, player)
        wield3d.update(player, {
            _wield3d_visual = "mesh",
            _wield3d_mesh = "pmb_fenn_spear.b3d",
            _wield3d_textures = "pmb_fenn_spear.png",
            _wield3d_rotation = {x=0, y=-60, z=-90},
            _wield3d_offset = {x=0, y=9.0, z=1},
            _wield3d_scale = {x=0.5, y=0.5, z=0.5}
        })
        return itemstack
    end,
    _cooldown = 1.5,
    _windup = 1,

    _prj_speed = 40,
    _wield3d_visual = "mesh",
    _wield3d_mesh = "pmb_fenn_spear.b3d",
    _wield3d_textures = "pmb_fenn_spear.png",
    _wield3d_rotation = {x=0, y=-60, z=-90},
    _wield3d_offset = {x=0, y=9.0, z=1},
    _wield3d_scale = {x=0.5, y=0.5, z=0.5}
})
