import * as mc from "@minecraft/server";
import * as utils from "../utils/index";
async function initializeBlaze() {
    await utils.waitForWorldLoad();
    utils.runCommand("event entity @e[type=ldz_240409:flame_vortex] despawn");
}
initializeBlaze();
export function onBlazeUse(player) {
    utils.mclog(`${player.nameTag} Used Blaze Weapon`);
    utils.modifyEquipmentDurability(player, mc.EquipmentSlot.Mainhand, -1);
    const vortex = new utils.SafetyCheckedEntity(player.dimension.spawnEntity("ldz_240409:flame_vortex", player.location));
    vortex.addEffect("slow_falling", 1000, { showParticles: false });
    vortex.runCommand("playsound ldz_240409:entity.flame_vortex.spawn @a ~ ~ ~");
    // const playerYRotation = player.getRotation().y;
    const moveDirection = player.getViewDirection();
    const endTick = mc.system.currentTick + 100;
    const movementThread = mc.system.runInterval(() => {
        if (!vortex.isValid()) {
            mc.system.clearRun(movementThread);
            return;
        }
        const inWaterOrRain = vortex.getProperty("ldz_240409:is_in_water_or_rain");
        if (inWaterOrRain) {
            for (let offset = 0; offset < 3; offset += 0.2) {
                const randomOffset = { x: Math.random() * 2 - 1, y: offset, z: Math.random() * 2 - 1 };
                vortex.runCommand(`particle minecraft:water_evaporation_bucket_emitter ${vortex.location.add(randomOffset)}`);
            }
            vortex.runCommand("playsound ldz_240409:entity.flame_vortex.extinguish @a ~ ~ ~");
            vortex.remove();
            utils.despawnOnReload(vortex);
            return;
        }
        if (vortex.isOnGround) {
            vortex.applyImpulse(moveDirection.multiply(0.2));
        }
        else {
            vortex.applyImpulse(moveDirection.multiply(0.04));
        }
    });
    const damageThread = mc.system.runInterval(() => {
        if (!vortex.isValid()) {
            mc.system.clearRun(damageThread);
            return;
        }
        utils.getEntitiesSafe(vortex.dimension, {
            location: vortex.location,
            maxDistance: 2.5,
            excludeTypes: ["minecraft:item", "ldz_240409:flame_vortex"]
        }).forEach(entity => {
            if (entity.id === player.id)
                return;
            try {
                entity.applyDamage(5, { cause: mc.EntityDamageCause.entityAttack, damagingEntity: player.UnsafeEntity });
                entity.setOnFire(5, true);
            }
            catch (error) {
                utils.mcwarn(`Cannot apply vortex damage to ${entity.typeId}`);
            }
        });
        if (mc.system.currentTick >= endTick) {
            mc.system.clearRun(damageThread);
            mc.world.playSound("ldz_240409:entity.flame_vortex.extinguish", vortex.location);
            vortex.remove();
            utils.despawnOnReload(vortex);
            return;
        }
    }, 10);
}
