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_void_scepter.dimension_rift"    
        })
        
        lib.animation(player, "animation.ld_eb_void_scepter_fpp.dimension_rift", itemStack.typeId, 1, false)
        lib.animation(player, "animation.ld_eb_void_scepter.dimension_rift", itemStack.typeId, 2, false)

        await mc.system.waitTicks(0.6 * 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.dimension_rift",
            player, 
            { z: 1, y: 0.1 },
            { y: player.getRotation().y+180 },
            true,
            false
        )
        spell.owner = player
        const tick = mc.system.runInterval(() => {
            if (!spell.isValid()) { return mc.system.clearRun(tick) }
            lib.rayCast(spell, 7, 1, 
                /** @param  { mc.Player } target */
                async 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)))*0.1),  {
                        cause: "contact",
                        damagingEntity: player
                    })
                    lib.middleImpulse(target, spell, 1 * target.typeId.startsWith("ld_eb:") ? 20: 1, 0.004)
                }
            )
        }, 0.1*20)

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