

export async function GrapplingHook(source, itemStack, useDuration) {
    const durability = itemStack.getComponent("minecraft:durability");

    if (itemStack.typeId === 'lv_mo:grappling_hook') {
        if (durability.damage === durability.maxDurability) {
            source.runCommandAsync(`replaceitem entity @s slot.weapon.mainhand 0 air`);
        } else {
            durability.damage += 1;
            source.getComponent('equippable').setEquipment('Mainhand', itemStack);
            projectileSpawn(source, `lv_mo:grappling_hook_projectile`, 2.5);
        }
    }
} 

function projectileSpawn(player, projectile, speedMultiplier = 3) {
    let coords = player.getHeadLocation();
    const grapplinghook = player.dimension.spawnEntity(projectile, {
        x: (coords.x + player.getViewDirection().x),
        y: (coords.y + player.getViewDirection().y),
        z: (coords.z + player.getViewDirection().z)
    });

    const projectileComp = grapplinghook.getComponent('minecraft:projectile');
    const leashable = grapplinghook.getComponent("leashable");
    leashable.leashTo(player);
    if (projectileComp) {
        projectileComp.owner = player;
    }
    grapplinghook.clearVelocity();
    grapplinghook.applyImpulse({
        x: player.getViewDirection().x * speedMultiplier,
        y: player.getViewDirection().y * speedMultiplier,
        z: player.getViewDirection().z * speedMultiplier
    });
}