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

const type = {
    delay: 4,
    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_metal_hammer.magnetic_slam"    
        })
        
        lib.animation(player, "animation.ld_eb_metal_hammer.magnetic_slam", itemStack.typeId, 1, false)
        lib.animation(player, "animation.ld_eb_metal_hammer_fpp.magnetic_slam", itemStack.typeId, 2, false)

        await mc.system.waitTicks(1 * 20)
        !mc.world.getDynamicProperty("ld_eb:efeitos_sonoros") ? null: player.playSound("ld_eb.rockpunch", { pitch: lib.random(0.9, 1.3) })
        /** @type { mc.Entity } */
        const spell = lib.spell(
            "ld_eb:ld_eb_metal_hammer.magnetic_slam",
            player, 
            { z: 2, y: 0.1, x: 0.25 },
            { y: player.getRotation().y+180 },
            false,
            false
        )
        spell.owner = player
        const locator = lib.locatorEntity(player, { z: 3 }, false, false)
        lib.rayCast(spell, 4, 3, 
            /** @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, spell, (lib.getDistance(spell.location, target.location)/2.5) * target.typeId.startsWith("ld_eb:") ? 20: 1, 0.3)
                target.addEffect("slowness", 2*20, {
                    amplifier: 1,
                    showParticles: false
                })
            }
        )

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