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

const type = {
    delay: 3,
    damage: lib.damage.baixo,
    damageMultiplier: 1.3
}

mc.Entity.prototype.owner = null
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_frostbound_glaive.chillwave"
    })

    lib.animation(player, "animation.ld_eb_frostbound_glaive.chillwave", itemStack.typeId, 1, false)
    lib.animation(player, "animation.ld_eb_frostbound_glaive_fpp.chillwave", itemStack.typeId, 2, false)

    await mc.system.waitTicks(0.6 * 20)
    /** @type { mc.Entity } */
    const spell = lib.spell(
        "ld_eb:ld_eb_frostbound_glaive.chillwave",
        player,
        { z: 2.5, y: 0.1 },
        { y: player.getRotation().y },
        false,
        false
    )
    !mc.world.getDynamicProperty("ld_eb:efeitos_sonoros") ? null : player.playSound("ld_eb.rockpunch", { pitch: lib.random(1, 1.5) })
    !mc.world.getDynamicProperty("ld_eb:efeitos_sonoros") ? null : player.playSound("ld_eb.ice_smash", { pitch: lib.random(0.9, 1.9) })
    spell.owner = player
    lib.middleImpulse(player, spell, -2, 0.1)
    lib.rayCast(spell, 8, 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, spell, -1, 0.3)
            if (target.typeId === "minecraft:player") {
                target.runCommand("/inputpermission set @s movement disabled");
                target.ld_eb_init_function("/inputpermission set @s movement enabled");

                mc.system.runTimeout(() => {
                    target.runCommand("/inputpermission set @s movement enabled");
                    target.ld_eb_remove_function("/inputpermission set @s movement enabled");
                }, 3 * 20);
            } else {
                target.addEffect("slowness", 3 * 20, {
                    amplifier: 255,
                    showParticles: false
                });
            }
        },
        [player]
    )

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