import { system, } from '@minecraft/server';
import { findNeighboringBlocks } from '../utils';
import { turnToFallingAsh } from '../../blocks/ash';
import createWitherWraithPortalEffect from '../../effects/witherWraithPortal';
const ASH_LEVEL_CENTER = 3;
const ASH_LEVEL_SIDE = 4;
function onTotemCompleteTransformation(lodestone) {
    system.runTimeout(() => {
        createWitherWraithPortalEffect({
            x: lodestone.x + 0.5,
            y: lodestone.y - 1,
            z: lodestone.z + 0.5,
            dimension: lodestone.dimension,
        });
    }, 6 * 20);
}
export default class TotemTransformationComponent {
    onTick(e) {
        // Find a totem block that can be converted into ash
        // eslint-disable-next-line no-unreachable-loop
        for (const block of findNeighboringBlocks(e.block, 'twb_wisu:corrupted_withered_bone_block')) {
            if (block.y === e.block.above()?.y) {
                block.setType('twb_wisu:soul_fire');
            }
            else if (block.y === e.block.below()?.y) {
                // Check whether the neighboring block is the block below us.
                // This whole block is a bit of a hacky way to make sure the lodestone is not the final
                // block we convert. Normally, the `findNeighboringBlock` iterator last finds the bottom
                // block of the totem. If we find this block, destroy the lodestone instead.
                e.block.setType('minecraft:air');
                turnToFallingAsh(e.block, ASH_LEVEL_CENTER);
                // The lodestone is what triggers this component however, so deleting it has the side effect
                // of stopping the tick event. Conveniently, converting both aligns perfectly with the SFX.
                block.setType('minecraft:air');
                turnToFallingAsh(block, ASH_LEVEL_CENTER);
                onTotemCompleteTransformation(e.block);
            }
            else {
                // Convert block to ash
                block.setType('minecraft:air');
                const isCenter = e.block.x === block.x && e.block.z === block.z;
                turnToFallingAsh(block, isCenter ? ASH_LEVEL_CENTER : ASH_LEVEL_SIDE);
            }
            // Return when a neighbor has been found
            return;
        }
        // If no neighbors are found, convert the lodestone.
        e.block.setType('minecraft:air');
        turnToFallingAsh(e.block, ASH_LEVEL_CENTER);
        onTotemCompleteTransformation(e.block);
    }
}
