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

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_molten_fists.lava_walls"    
        })
        
        lib.animation(player, "animation.ld_eb_molten_fists_fpp.lava_walls", itemStack.typeId, 1, false)
        lib.animation(player, "animation.ld_eb_molten_fists.lava_walls", itemStack.typeId, 2, false)

        await mc.system.waitTicks(0.4 * 20)
        !mc.world.getDynamicProperty("ld_eb:efeitos_sonoros") ? null: player.playSound("ld_eb.fire_ball", { pitch: lib.random(0.8, 0.9) })
        !mc.world.getDynamicProperty("ld_eb:efeitos_sonoros") ? null: player.playSound("ld_eb.rockpunch", { pitch: lib.random(0.9, 1) })
        /** @type { mc.Entity } */
        const spell = lib.spell(
            "ld_eb:ld_eb_molten_fists.lava_walls",
            player, 
            { z: 1, y: 0.1 },
            { y: player.getRotation().y+180 },
            true,
            false
        )
        spell.owner = player

        lib.rayCast(spell, 5, 3, 
            /** @param  { mc.Entity } target */
            function(target) { 
                target.setOnFire(5)
                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
                })
                try { target.applyKnockback(spell.getViewDirection().x, spell.getViewDirection().z, 6 * target.typeId.startsWith("ld_eb:") ? 90 : 4, 0.2) } catch {}
                target.addEffect("slowness", 2*20, {
                    amplifier: 1,
                    showParticles: false
                })
            }
        )

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