import * as mc from "@minecraft/server"
import { itemStack, startAnimations } from "./item"
import * as lib from "../../lib"

const type = {
    delay: 5,
    damage: lib.damage.moderado,
    damageMultiplier: 1.3
}

mc.world.afterEvents.itemUse.subscribe(async data => {
    const item = data.itemStack,
        player = data.source
        if (item.typeId !== itemStack.typeId) return
        if (player.getItemCooldown(item.typeId) !== 0) return
        if (player.isSneaking || !player.isOnGround) return
        player.startItemCooldown(item.typeId, type.delay*20)
        player.onScreenDisplay.setActionBar({
            translate: "actionbar.ld_eb:ld_eb_void_scepter.void_pulse"    
        })
        
        lib.animation(player, "animation.ld_eb_void_scepter_fpp.void_pulse", itemStack.typeId, 1, false)
        lib.animation(player, "animation.ld_eb_void_scepter.void_pulse", itemStack.typeId, 2, false)

        await mc.system.waitTicks(0.4 * 20)
        !mc.world.getDynamicProperty("ld_eb:efeitos_sonoros") ? null: player.playSound("ld_eb.airblow", { pitch: lib.random(0.6, 0.7) })
        /** @type { mc.Entity } */
        const spell = lib.spell(
            "ld_eb:ld_eb_void_scepter.void_pulse",
            player, 
            { z: 0, y: 0.1 },
            { y: player.getRotation().y+180 },
            false,
            false
        )
        spell.owner = player
        const locator = lib.locatorEntity(player, { z: 0 }, false, false)
        lib.rayCast(spell, 4, 1, 
            /** @param  { mc.Entity } target */
            function(target) {
                target.applyDamage(type.damage + ((type.damageMultiplier - 1) + ((type.damage * (player.getDynamicProperty(item.typeId + ".lvl") >= 10 ? 3: player.getDynamicProperty(item.typeId + ".lvl") >= 5 ? 2: 1) - type.damage))),  {
                    cause: "contact",
                    damagingEntity: player
                })
                lib.middleImpulse(target, locator, -2, 0.3)
                target.addEffect("slowness", 2*20, {
                    amplifier: 1,
                    showParticles: false
                })
            }
        )

        await mc.system.waitTicks(0.2 * 20)
        spell.remove()
        locator.remove()
        startAnimations(player)
})