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 aom_combat.cooldown.can_use(itemstack) then
        itemstack = aom_combat.cooldown.wear_start(itemstack, "windup")
        minetest.sound_play(("aom_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("aom_fenn:spear", {
    description = S("Fenn Spear"),
    inventory_image = "aom_fenn_spear_inv.png",
    groups = { not_in_creative_inventory = 1 },
    range = 0,
    on_secondary_use = function(itemstack, user, pointed_thing)
        return aom_combat.cooldown.attempt_to_use(itemstack, user, pointed_thing)
    end,
    on_place = function(itemstack, user, pointed_thing)
        return aom_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, "aom_fenn_spear_aim")
        itemstack = aom_combat.cooldown.windup_cancel(itemstack, player) or itemstack
        return aom_combat.cooldown.on_wield_change_from(itemstack, player)
    end,
    on_step = function(itemstack, player, dtime)
        local just_thrown = false
        itemstack, just_thrown = aom_combat.throwable.on_wield_throwable(player, "aom_fenn:spear_ENTITY", itemstack, {
            allow_partial_throw = true
        })
        if just_thrown then
            wield3d.update(player, {
                _wield3d_textures = "blank.png",
            })
            player_model.unset_anim(player, "aom_fenn_spear_aim")
            minetest.sound_play(("aom_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 = "aom_fenn_spear.b3d",
            _wield3d_textures = "aom_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 = "aom_fenn_spear.b3d",
    _wield3d_textures = "aom_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}
})
