import { ItemStack, Player, system } from "@minecraft/server"
import { addDamageItem, shootProjectileWithPower } from "../../library/itemManager";
import { getGamemode } from "../../library/worldFuntions";


/**
 * Evento del componente plasmaWeaponSmgComponent
 * @param {{itemStack: ItemStack, source: Player}} event 
 */
export const plasmaWeaponSmgEvent = ({ itemStack, source }) => {
    const currentDamage = itemStack.getComponent('minecraft:durability').damage;
    const maxDurability = itemStack.getComponent('minecraft:durability').maxDurability;
    const durability = maxDurability - currentDamage;
    const gamemode = getGamemode(source)
    if(durability > 1) {
        if(gamemode === 'survival' || gamemode === 'adventure') {
            addDamageItem(itemStack, source, 1);
        }
        source.runCommand('playanimation @s animation.player_fast_plasma_weapon_hold fast 1');
        shootProjectileWithPower(source, "nps_ec:plasma<nps_ec:plasma_fast_short>", 2);
        system.runTimeout(() => {
            shootProjectileWithPower(source, "nps_ec:plasma<nps_ec:plasma_fast>", 7.5);
        }, 5)
        source.runCommand('playsound shoot.plasma @a [r=5] ~ ~ ~ 0.7')
    } else {
        const offHand = source.getComponent('equippable').getEquipment('Offhand')
        if(!offHand) {
            source.runCommand('playsound shoot.locked @a [r=5] ~ ~ ~ 0.7');
            return
        }

        if(offHand.typeId !== 'nps_ec:plasma_capsule') {
            source.runCommand('playsound shoot.locked @a [r=5] ~ ~ ~ 0.7');
            return
        }

        source.runCommand('replaceitem entity @s slot.weapon.mainhand 1 nps_ec:fast_plasma_weapon');
        source.runCommand('clear @s nps_ec:plasma_capsule 0 1')

        source.runCommand('playanimation @s animation.player_fast_plasma_weapon_hold fast 1');
        shootProjectileWithPower(source, "nps_ec:plasma<nps_ec:plasma_fast_short>", 2);
        system.runTimeout(() => {
            shootProjectileWithPower(source, "nps_ec:plasma<nps_ec:plasma_fast>", 7.5);
        }, 5)
        source.runCommand('playsound shoot.plasma @a [r=5] ~ ~ ~ 0.7')
    }
}