import * as mc from '@minecraft/server';


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

    if (itemStack.typeId === 'lv_mo:neptune_trident') {
        source.playAnimation(`animation.lv_mo.player.neptune_trident.thrid.throw`, {
            controller: `neptune_trident.thrid.charge`,
            blendOutTime: 0.01,
            stopExpression: `q.any_animation_finished`,
            nextState: `none`
        });
        if (durability.damage === durability.maxDurability) {
            source.runCommandAsync(`replaceitem entity @s slot.weapon.mainhand 0 air`);
        } else {
            durability.damage += 1;
            const currentDamage = durability.damage;

            const newItem = new mc.ItemStack('lv_mo:neptune_trident', 1);
            const newDurability = newItem.getComponent("minecraft:durability");
            newDurability.damage = currentDamage;

            projectileSpawn(source, `lv_mo:neptune_trident_projectile`, 2.5, currentDamage);
            equippable.setEquipment('Mainhand', null);
        }
    }
}
function projectileSpawn(player, projectile, speedMultiplier = 3, currentDamage) {
    let coords = player.getHeadLocation();
    const neptunetrident = player.dimension.spawnEntity(projectile, {
        x: (coords.x + player.getViewDirection().x),
        y: (coords.y + player.getViewDirection().y),
        z: (coords.z + player.getViewDirection().z)
    });

    const projectileComp = neptunetrident.getComponent('minecraft:projectile');
    if (projectileComp) {
        projectileComp.owner = player;
    }
    neptunetrident.setDynamicProperty('projectileDamage', currentDamage);

    neptunetrident.clearVelocity();
    neptunetrident.applyImpulse({
        x: player.getViewDirection().x * speedMultiplier,
        y: player.getViewDirection().y * speedMultiplier,
        z: player.getViewDirection().z * speedMultiplier
    });
}