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 + 1.6
    return eyepos
end

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

    local pos = get_eyepos(player)
    local dir = player:get_look_dir()
    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
    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)
    local just_thrown = false

    if cl and cl.just_released.place then
        local meta = itemstack:get_meta()
        if ((flags.allow_partial_throw and meta:get_string("_mode") == "windup")
        or meta:get_string("_windup_complete") == "true") 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.wear_start(itemstack, "cooldown")
                return itemstack, false
            end

            meta:set_string("_windup_complete", "")
            just_thrown = true
            pmb_combat.throwable.throw(player, entname, itemstack, {
                speed_mult = wear_factor,
                damage_mult = wear_factor,
            })
            itemstack = pmb_combat.cooldown.wear_start(itemstack, "cooldown")
        end
    elseif cl and not cl.ctrl.place then
        local meta = itemstack:get_meta()
        meta:set_string("_windup_complete", "")
    end
    return itemstack, just_thrown
end




function pmb_combat.throwable.register_throwable(name, def)
    def.cooldown = def.cooldown or 2
    def.windup = def.windup or 0.5
    pmb_combat.cooldown.register_cooldown(name, def)
end

