
import {ItemStack, world, system, Direction, EquipmentSlot} from '@minecraft/server';


world.afterEvents.itemUse.subscribe((data) => {
    const item = data.itemStack;
    const player = data.source;


    if (item.typeId === "lscrew_mocr:alien_blaster") {
        let cooldown = item.getComponent("minecraft:cooldown");
        let time = cooldown.getCooldownTicksRemaining(player)
        let durability = item.getComponent("minecraft:durability");
        let equippable = player.getComponent("minecraft:equippable");
        const damage_value = 2;
        if (time == 0) {
        shootProjectile(player, "lscrew_mocr:blaster_charge", 2);
        cooldown.startCooldown(player);
        if (durability.damage + damage_value >= durability.maxDurability)
        {
            equippable.setEquipment(EquipmentSlot.Mainhand, undefined);
        } else {
            durability.damage += damage_value;
            equippable.setEquipment(EquipmentSlot.Mainhand, item);
            
            
            
        }

        }
    }
});

/**
 * @param {Player} player
 * @param {Entity} projectileType
 * @param {number?} power 
 */
function shootProjectile(player, projectileType, power) {

    const view = player.getViewDirection(),
    head = player.getHeadLocation(),
    direction = { x: head.x + view.x, y: head.y + view.y, z: head.z + view.z },
    velocity = { x: view.x * power, y: view.y * power, z: view.z * power };
const projectile = player.dimension.spawnEntity(projectileType, direction).getComponent("minecraft:projectile");
projectile.shoot(velocity)
projectile.owner = player
};
