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


pmb_combat.throwable = {}


local MAX_WEAR = 65534


local function get_eyepos(player)
    local eyepos = vector.add(player:get_pos(), vector.multiply(player:get_eye_offset(), 0.1))
    eyepos.y = eyepos.y + player:get_properties().eye_height
    return eyepos
end

function pmb_combat.throwable.throw(player, entname, itemstack, flags)
    if not flags then flags = {} end
    local def = itemstack and itemstack:get_definition()
    if not def then minetest.log("error", "NO DEF FOR TOOL") return end

    local pos = get_eyepos(player)
    local dir = player:get_look_dir()
    if def._prj_inaccuracy then
        dir = vector.offset(dir,
            (math.random()*2-1) * def._prj_inaccuracy,
            (math.random()*2-1) * def._prj_inaccuracy,
            (math.random()*2-1) * def._prj_inaccuracy
        )
    end
    local ent = pmb_combat.projectile.add_projectile(player,
        entname,
        pos, dir, (flags.speed or def._prj_speed or 10) * (flags.speed_mult or 1)
    )
    if flags.damage_mult and ent._prj_damage_groups then
        local tab = {}
        for i, val in pairs(ent._prj_damage_groups) do
            tab[i] = flags.damage_mult * val
        end
        ent._prj_damage_groups = tab
    end
    if def._prj_on_throw then
        def._prj_on_throw(ent, itemstack, player)
    end
    return ent
end


function pmb_combat.throwable.on_wield_throwable(player, entname, itemstack, flags)
    if not flags then flags = {} end

    local cl = player_info.get(player)
    if not cl then return itemstack, false end
    local just_thrown = false

    local meta = itemstack:get_meta()
    local mode = meta:get_string("_mode") or ""

    if cl.just_pressed.place and mode == "" then
        itemstack = pmb_combat.cooldown.windup_start(itemstack, player)
    end

    if cl and cl.just_released.place then
        if (mode == "complete") or (flags.allow_partial_throw and mode == "windup") then

            local wear = itemstack:get_wear()
            local wear_factor = 1 - wear / MAX_WEAR
            if wear_factor < (flags.min_windup or 0) then
                itemstack = pmb_combat.cooldown.cooldown_start(itemstack, player)
                return itemstack, false
            end

            just_thrown = true
            pmb_combat.throwable.throw(player, entname, itemstack, {
                speed_mult = wear_factor,
                damage_mult = wear_factor,
            })
            itemstack = pmb_combat.cooldown.cooldown_start(itemstack, player)
        end
    elseif cl and not cl.ctrl.place then
        -- itemstack = pmb_combat.cooldown.cooldown_start(itemstack, player)
    end
    return itemstack, just_thrown
end
