import { Direction, EntityDamageCause, EntityHealthComponent, EntitySkinIdComponent, EntityVariantComponent, EquipmentSlot, MinecraftDimensionTypes, StructureRotation, system, world } from "@minecraft/server";
import config from "nps_tbe/config";
import { applyItemDamage, damageItemStack, getBlockState, getCardinalDirection, getPlayerEquipment, getRandomInt, getScoreboard, hasEquippedElytra, isInRange, setBlockState } from "nps_tbe/others/my_API";
import { parameterNames, Settings } from "./essentials";
world.afterEvents.entityHurt.subscribe(event => {
    SporeBone.afterEntityHurt(event);
});
world.afterEvents.entityHealthChanged.subscribe(event => {
    LifeRegenerationSystem.afterEntityHealthChanged(event);
});
world.afterEvents.projectileHitBlock.subscribe(event => {
    StormCharge.afterProjectileHitBlock(event);
});
world.afterEvents.projectileHitEntity.subscribe(event => {
    StormCharge.afterProjectileHitEntity(event);
});
world.afterEvents.dataDrivenEntityTrigger.subscribe(event => {
    EndDimension.afterDataDrivenEntityTrigger(event);
});
world.afterEvents.entityHurt.subscribe(event => {
    VoidTotem.afterEntityHurt(event);
});
world.beforeEvents.entityRemove.subscribe(event => {
    slimeSeparation(event);
});
world.afterEvents.entityHurt.subscribe(event => {
    DamageIndicators.afterEntityHurt(event);
});
world.afterEvents.entityHealthChanged.subscribe(event => {
    LifeIndicators.updateEntityNameTag(event.entity);
});
world.afterEvents.entitySpawn.subscribe(event => {
    if (!event.entity)
        return;
    if (!event.entity.isValid())
        return;
    if (event.entity.matches({ families: ["slime"] })) {
        event.entity.runCommand('/effect @s instant_health 1 0 true');
    }
    LifeIndicators.updateEntityNameTag(event.entity);
});
world.beforeEvents.worldInitialize.subscribe(event => {
    AetherWand.initialize(event);
    Cactus.initialize(event);
    EndFungus.initialize(event);
    FoodEffects.initialize(event);
    SBK_01.initialize(event);
    SBK_02.initialize(event);
    SkiropteronEgg.initialize(event);
    SwaperSpawner.initialize(event);
    FakeChest.initialize(event);
});
world.afterEvents.playerBreakBlock.subscribe(event => {
    EggShell.afterPlayerBreakBlock(event);
});
//..
function slimeSeparation(event) {
    if (!event.removedEntity.matches({ families: ["nps_tbe:slime"] })) {
        return;
    }
    const slime = event.removedEntity;
    if (slime.location.y < 0 && slime.dimension.id == MinecraftDimensionTypes.theEnd) {
        return;
    }
    const evc = slime.getComponent(EntityVariantComponent.componentId);
    const slimeSize = evc.value;
    if (slimeSize == 1) {
        return;
    }
    const newSlimeSize = Math.round(slimeSize / 2);
    const slimNumber = getRandomInt(2, 4);
    const slimeTypeId = slime.typeId;
    const location = slime.location;
    const dimension = slime.dimension;
    system.run(() => {
        try {
            for (let i = 0; i < slimNumber; i++) {
                const newSlime = dimension.spawnEntity(slimeTypeId, location);
                if (newSlimeSize == 1) {
                    newSlime.triggerEvent("spawn_small");
                }
                else {
                    newSlime.triggerEvent("spawn_medium");
                }
            }
        }
        catch { }
    });
}
class DamageIndicators {
    static afterEntityHurt(event) {
        const damageIndicator = Settings.getValue(parameterNames.damageIndicators);
        if (damageIndicator == 0) {
            return;
        }
        const hurtEntity = event.hurtEntity;
        if (!hurtEntity.isValid()) {
            return;
        }
        const damage = event.damage;
        if (damage < 0) {
            return;
        }
        try {
            this.spawnDamageIndicator(hurtEntity.dimension, hurtEntity.location, damage);
        }
        catch (error) { }
    }
    static spawnDamageIndicator(dimension, location, damage) {
        const DAMAGE_INDICATOR_TYPE_ID = `nps_tbe:damage_indicator`;
        const y = location.y + 1.5;
        const inRange = isInRange(y, dimension.heightRange.min, dimension.heightRange.max);
        if (!inRange) {
            return;
        }
        const damage_indicator = dimension.spawnEntity(DAMAGE_INDICATOR_TYPE_ID, { x: location.x, y: y, z: location.z });
        let skin_id = damage_indicator.getComponent(EntitySkinIdComponent.componentId);
        skin_id.value = damage;
    }
}
class LifeIndicators {
    static updateEntityNameTag(hurtEntity) {
        if (!hurtEntity)
            return;
        if (!hurtEntity.isValid())
            return;
        const lifeIndicators = Settings.getValue(parameterNames.lifeIndicators);
        const entityNameIndicators = Settings.getValue(parameterNames.entityNameIndicators);
        if (hurtEntity.nameTag && !hurtEntity.nameTag.startsWith(''))
            return;
        if (lifeIndicators == 0 && entityNameIndicators == 0) {
            if (!hurtEntity.nameTag)
                return;
            hurtEntity.nameTag = '';
            return;
        }
        const excludeTypes = [
            "minecraft:armor_stand",
            "minecraft:ender_dragon",
            "minecraft:item",
            "minecraft:player",
            "minecraft:wither",
            "nps_tbe:storm_charge_projectile",
            "nps_tbe:damage_indicator",
            "nps_tbe:giant_amanita_sporebone",
            "nps_tbe:giant_chlorophos_sporebone",
            "nps_tbe:giant_cortinarius_sporebone",
            "nps_tbe:giant_lactarius_sporebone",
            "nps_tbe:mimic"
        ];
        const resetTypes = [
            "nps_tbe:giant_amanita_sporebone",
            "nps_tbe:giant_chlorophos_sporebone",
            "nps_tbe:giant_cortinarius_sporebone",
            "nps_tbe:giant_lactarius_sporebone"
        ];
        if (resetTypes.includes(hurtEntity.typeId)) {
            if (hurtEntity.nameTag && hurtEntity.nameTag.startsWith('')) {
                hurtEntity.nameTag = "";
            }
        }
        if (excludeTypes.includes(hurtEntity.typeId))
            return;
        const ehc = hurtEntity.getComponent(EntityHealthComponent.componentId);
        if (!ehc)
            return;
        const hp = ehc.currentValue;
        const hpmax = ehc.effectiveMax;
        const entityName = LifeIndicators.formatEntityName(hurtEntity.typeId);
        const textColor = LifeIndicators.getHealthTextColor(hp, hpmax);
        if (lifeIndicators && entityNameIndicators) {
            hurtEntity.nameTag = `${entityName}\n§r${textColor}${Math.ceil(hp)}/${Math.ceil(hpmax)}§r`;
        }
        else if (lifeIndicators && !entityNameIndicators) {
            hurtEntity.nameTag = `§r${textColor}${Math.ceil(hp)}/${Math.ceil(hpmax)}§r`;
        }
        else {
            hurtEntity.nameTag = `${entityName}`;
        }
    }
    static formatEntityName(typeId) {
        // Split the typeId at ':' and take the second part
        const rawName = typeId.split(':')[1];
        // Replace underscores with spaces, split into words, capitalize each, and join with spaces
        return rawName
            .split('_')
            .map(word => word.charAt(0).toUpperCase() + word.slice(1))
            .join(' ');
    }
    static getHealthTextColor(hp, hpmax) {
        const percentage = (hp / hpmax) * 100;
        if (percentage > 66) {
            return "§a"; // Green for more than 66% HP
        }
        else if (percentage > 33) {
            return "§e"; // Yellow for 33% to 66% HP
        }
        else {
            return "§c"; // Red for less than 33% HP
        }
    }
}
class VoidTotem {
    static afterEntityHurt(event) {
        if (event.hurtEntity.typeId != "minecraft:player")
            return;
        const player = event.hurtEntity;
        const cause = event.damageSource.cause;
        if (cause == EntityDamageCause.void) {
            const offHand = getPlayerEquipment(player).getEquipment(EquipmentSlot.Offhand);
            if (offHand?.typeId != "nps_tbe:void_totem")
                return;
            const dimension = event.hurtEntity.dimension;
            let safeLocation = null;
            const radius = 50; // Rayon de la zone circulaire
            const centerX = player.location.x;
            const centerZ = player.location.z;
            // Générer des coordonnées aléatoires dans une zone circulaire
            for (let i = 0; i < 100; i++) { // Limiter à 100 tentatives
                const angle = Math.random() * 2 * Math.PI;
                const distance = Math.random() * radius;
                const randomX = centerX + Math.cos(angle) * distance;
                const randomZ = centerZ + Math.sin(angle) * distance;
                const topBlock = dimension.getTopmostBlock({
                    x: randomX,
                    z: randomZ
                });
                if (topBlock && !topBlock.isAir) {
                    safeLocation = topBlock.above().location;
                    break;
                }
                if (safeLocation)
                    break;
            }
            let finalLocation = safeLocation || player.getSpawnPoint() || world.getDefaultSpawnLocation();
            player.teleport(finalLocation);
            const voidTotem = applyItemDamage(player, getPlayerEquipment(player).getEquipment(EquipmentSlot.Offhand), 1);
            getPlayerEquipment(player).setEquipment(EquipmentSlot.Offhand, voidTotem);
            system.runTimeout(() => {
                player.dimension.spawnParticle("nps_tbe:void_totem", finalLocation);
                player.playSound('random.break', { location: finalLocation });
                player.playSound("random.totem", { pitch: 1.25, volume: 1.0, location: finalLocation });
            }, 1);
        }
    }
}
class EggShell {
    static afterPlayerBreakBlock(event) {
        if (event.brokenBlockPermutation.type.id != "nps_tbe:eggshell_block")
            return;
        const spawnChance = 0.10;
        if (Math.random() > spawnChance)
            return;
        event.block.dimension.spawnEntity("nps_tbe:giant_endermite", event.block.center());
    }
}
class EndDimension {
    static afterDataDrivenEntityTrigger(event) {
        if (event.entity.typeId == "minecraft:ender_dragon" && event.eventId == "minecraft:entity_spawned") {
            try {
                EndDimension.reloadEndPillars();
            }
            catch { }
        }
    }
    static reloadEndPillars() {
        const structureIdentifier = "mystructure:nps_tbe/end_pillar";
        const structureLocationXZ = [
            { x: 12, z: -39 },
            { x: 33, z: -24 },
            { x: 41, z: 0 }, { x: 42, z: 0 },
            { x: 33, z: 24 },
            { x: 12, z: 39 },
            { x: -12, z: 39 },
            { x: -33, z: 24 },
            { x: -41, z: 0 }, { x: -42, z: 0 },
            { x: -33, z: -24 },
            { x: -12, z: -39 }
        ];
        const endDimension = world.getDimension(MinecraftDimensionTypes.theEnd);
        endDimension.runCommand("/tickingarea add -80 0 -80 79 0 79 nps_tbe:20940a8b");
        system.runTimeout(() => {
            structureLocationXZ.forEach(structureLocation => {
                try {
                    EndDimension.reloadEndPillar(structureIdentifier, structureLocation);
                }
                catch { }
            });
            endDimension.runCommand("/tickingarea remove nps_tbe:20940a8b");
        }, 10);
    }
    static reloadEndPillar(structureIdentifier, structureLocationXZ) {
        const endDimension = world.getDimension(MinecraftDimensionTypes.theEnd);
        const structure = world.structureManager.get(structureIdentifier);
        const { x: structureX, y: structureY } = structure.size;
        const XZoffset = Math.floor(structureX / 2);
        let yBedrock = endDimension.heightRange.min;
        let block = undefined;
        while (yBedrock < endDimension.heightRange.max && (block = endDimension.getBlock({
            x: structureLocationXZ.x,
            y: yBedrock,
            z: structureLocationXZ.z
        }))?.typeId !== "minecraft:bedrock") {
            yBedrock++;
        }
        if (block?.typeId === "minecraft:bedrock") {
            world.structureManager.place(structureIdentifier, endDimension, {
                x: structureLocationXZ.x - XZoffset,
                y: yBedrock - structureY + 5,
                z: structureLocationXZ.z - XZoffset
            });
        }
    }
}
class StormCharge {
    static afterProjectileHitEntity(event) {
        if (this.isProjectileStormCharge(event.projectile)) {
            this.onStormChargeHit(event.dimension, event.location);
        }
    }
    static afterProjectileHitBlock(event) {
        if (this.isProjectileStormCharge(event.projectile)) {
            this.onStormChargeHit(event.dimension, event.location);
        }
    }
    static isProjectileStormCharge(projectile) {
        return projectile?.typeId == "nps_tbe:storm_charge_projectile";
    }
    static onStormChargeHit(dimension, location) {
        const soundId = "";
        const effectName = "nps_tbe:lightning_area";
        try {
            dimension.playSound(soundId, location);
            dimension.spawnParticle(effectName, location);
        }
        catch { }
    }
}
class LifeRegenerationSystem {
    static isMonsterRegenEnabled() {
        const monsterRegen = Settings.getValue(parameterNames.monsterRegen);
        return monsterRegen == 1;
    }
    static afterEntityHealthChanged(event) {
        if (!this.isMonsterRegenEnabled())
            return;
        if (event.newValue >= event.oldValue)
            return;
        const scoreboard = getScoreboard(config.regenerationTimerObjectiveId);
        try {
            scoreboard.setScore(event.entity, 8);
        }
        catch { }
    }
    static runInterval() {
        if (!this.isMonsterRegenEnabled())
            return;
        const scoreboard = getScoreboard(config.regenerationTimerObjectiveId);
        const participants = scoreboard.getParticipants();
        for (const participant of participants) {
            const score = scoreboard.getScore(participant) - 1;
            if (score <= 0) {
                scoreboard.removeParticipant(participant);
            }
            else {
                scoreboard.setScore(participant, score);
            }
        }
        const dimensions = [
            MinecraftDimensionTypes.overworld,
            MinecraftDimensionTypes.nether,
            MinecraftDimensionTypes.theEnd
        ];
        const nonRegeneratingEntities = new Set([
            "minecraft:player",
            "minecraft:item"
        ]);
        for (const dimension of dimensions) {
            const entities = world.getDimension(dimension).getEntities();
            for (const entity of entities) {
                if (scoreboard.hasParticipant(entity))
                    continue;
                if (nonRegeneratingEntities.has(entity.typeId))
                    continue; // Exclure les entités spécifiques
                const ehc = entity.getComponent(EntityHealthComponent.componentId);
                if (!ehc)
                    continue;
                const carePoints = Math.ceil(ehc.effectiveMax * 0.0125);
                ehc.setCurrentValue(Math.max(1, Math.min(ehc.currentValue + carePoints, ehc.effectiveMax)));
            }
        }
    }
}
LifeRegenerationSystem.tickInterval = 20;
system.runInterval(() => {
    LifeRegenerationSystem.runInterval();
}, LifeRegenerationSystem.tickInterval);
class EndFungus {
    static initialize(event) { event.itemComponentRegistry.registerCustomComponent(this.componentName, new this()); }
    onCompleteUse(arg) {
        const player = arg.source;
        if (Math.random() < 0.75)
            return;
        player.addEffect("darkness", 20 * 8, {
            amplifier: 0,
            showParticles: true
        });
    }
}
EndFungus.componentName = "nps_tbe:37983d81";
class AetherWand {
    static initialize(event) { event.itemComponentRegistry.registerCustomComponent(this.componentName, new this()); }
    onUse(arg) {
        const player = arg.source;
        player.runCommandAsync("particle nps_tbe:wands_0_impact  ~ ~0.5 ~");
        player.runCommandAsync("playsound random.explode @a[r=10] ~ ~ ~ 1 1.5 1");
        player.applyKnockback(player.getViewDirection().x, player.getViewDirection().z, 7, 2);
        const mustApplyEffects = !hasEquippedElytra(player);
        if (mustApplyEffects) {
            player.addEffect("slow_falling", 10 * 20);
        }
        damageItemStack(arg.source);
    }
    ;
}
AetherWand.componentName = "nps_tbe:1d42108f";
class Cactus {
    static initialize(event) { event.itemComponentRegistry.registerCustomComponent(this.componentName, new this()); }
    onCompleteUse(arg) {
        const player = arg.source;
        player.runCommand('/damage @s 2 thorns');
    }
}
Cactus.componentName = "nps_tbe:8efcce32";
class FoodEffects {
    static initialize(event) { event.itemComponentRegistry.registerCustomComponent(this.componentName, new this()); }
    onCompleteUse(arg) {
        const player = arg.source;
        const itemStack = arg.itemStack;
        if (!itemStack)
            return;
        FoodEffects.applyEffects(itemStack.typeId, player);
    }
    static getEffects(itemName) {
        return this.foodEffects[itemName] ?? [];
    }
    static applyEffects(itemName, player) {
        const effects = this.getEffects(itemName);
        for (const eff of effects) {
            if (Math.random() <= eff.probability) {
                player.addEffect(eff.effect, eff.duration * 20, // Convert seconds to ticks
                {
                    amplifier: eff.amplifier,
                    showParticles: eff.showParticles
                });
            }
        }
    }
}
FoodEffects.componentName = "nps_tbe:0c7756ff";
FoodEffects.foodEffects = {
    "nps_tbe:luma_swirl_jelly": [
        { effect: "regeneration", duration: 6, amplifier: 1, showParticles: true, probability: 1.0 },
        { effect: "resistance", duration: 30, amplifier: 1, showParticles: true, probability: 1.0 },
        { effect: "speed", duration: 30, amplifier: 1, showParticles: true, probability: 1.0 }
    ],
    "nps_tbe:fusion_glaze_jelly": [
        { effect: "regeneration", duration: 6, amplifier: 1, showParticles: true, probability: 1.0 },
        { effect: "jump_boost", duration: 30, amplifier: 12, showParticles: true, probability: 1.0 },
        { effect: "slow_falling", duration: 30, amplifier: 4, showParticles: true, probability: 1.0 }
    ],
    "nps_tbe:solar_bloom_jelly": [
        { effect: "regeneration", duration: 6, amplifier: 1, showParticles: true, probability: 1.0 },
        { effect: "fire_resistance", duration: 30, amplifier: 0, showParticles: true, probability: 1.0 },
        { effect: "strength", duration: 30, amplifier: 1, showParticles: true, probability: 1.0 }
    ],
};
class SporeBone {
    static afterEntityHurt(event) {
        const entityTypeId = event.hurtEntity.typeId;
        const tablePath = this.MUSHROOM_LOOT_TABLE_MAP[entityTypeId];
        if (!tablePath)
            return;
        const { x, y, z } = event.hurtEntity.location;
        const dimension = event.hurtEntity.dimension;
        // Summon loot
        const lootCommand = `loot spawn ${Math.floor(x)} ${Math.floor(y)} ${Math.floor(z)} loot "${tablePath}"`;
        dimension.runCommand(lootCommand);
    }
}
SporeBone.MUSHROOM_LOOT_TABLE_MAP = {
    "nps_tbe:amanita_sporebone": "nps/tbe/entities/amanita_fungus",
    "nps_tbe:cortinarius_sporebone": "nps/tbe/entities/cortinarius_fungus",
    "nps_tbe:lactarius_sporebone": "nps/tbe/entities/lactarius_fungus",
    "nps_tbe:chlorophos_sporebone": "nps/tbe/entities/chlorophos_fungus",
    "nps_tbe:giant_amanita_sporebone": "nps/tbe/entities/amanita_mushroom_block",
    "nps_tbe:giant_cortinarius_sporebone": "nps/tbe/entities/cortinarius_mushroom_block",
    "nps_tbe:giant_lactarius_sporebone": "nps/tbe/entities/lactarius_mushroom_block",
    "nps_tbe:giant_chlorophos_sporebone": "nps/tbe/entities/chlorophos_mushroom_block"
};
class SkiropteronEgg {
    static initialize(event) { event.blockComponentRegistry.registerCustomComponent(this.componentName, new this()); }
    onRandomTick(arg) {
        const block = arg.block;
        const canGrow = SkiropteronEgg.isOnHayBlock(block);
        if (!canGrow)
            return;
        const cracked_state = getBlockState(block, "nps_tbe:cracked_state");
        if (cracked_state == 4) {
            arg.dimension.playSound("block.sniffer_egg.hatch", block.location, { volume: 3.0, pitch: 1.1 });
            block.setType("minecraft:air");
            arg.dimension.spawnEntity("nps_tbe:skiropteron<nps_tbe:skiropteron_born>", block.center());
        }
        else {
            arg.dimension.playSound("block.sniffer_egg.crack", block.location, { volume: 3.0, pitch: 1.1 });
            setBlockState(block, "nps_tbe:cracked_state", cracked_state + 1);
        }
    }
    ;
    static isOnHayBlock(block) {
        if (!block)
            return false;
        const blockBelow = block.below();
        if (!blockBelow)
            return false;
        return blockBelow.typeId == "minecraft:hay_block";
    }
}
SkiropteronEgg.componentName = "nps_tbe:d5346c5f";
class SwaperSpawner {
    static initialize(event) { event.blockComponentRegistry.registerCustomComponent(this.componentName, new this()); }
    onTick(arg) {
        const nearbyPlayers = arg.dimension.getPlayers({
            maxDistance: 16,
            location: arg.block.location,
            excludeTags: [config.developerTag]
        });
        if (nearbyPlayers.length == 0)
            return;
        const blockAbove = arg.block.above();
        if (!blockAbove)
            return;
        if (!blockAbove.isAir)
            return;
        arg.dimension.spawnEntity("nps_tbe:swapper", blockAbove.center());
        arg.block.setType("minecraft:purpur_block");
    }
    ;
}
SwaperSpawner.componentName = "nps_tbe:9b7ffa7f";
class FakeChest {
    static initialize(event) { event.blockComponentRegistry.registerCustomComponent(this.componentName, new this()); }
    onTick(arg) {
        const dimension = arg.dimension;
        const block = arg.block;
        const nearbyPlayer = dimension.getPlayers({
            location: block.location,
            maxDistance: 64,
            tags: [config.developerTag]
        });
        if (nearbyPlayer.length > 0)
            return;
        const cardinalDirection = getCardinalDirection(block);
        block.setType("minecraft:air");
        const chestTransformationChance = 0.5;
        if (Math.random() <= chestTransformationChance) {
            //chest
            const structureRotation = FakeChest.getStructureRotation(cardinalDirection);
            world.structureManager.place("nps_tbe/mimic_chest", dimension, block.location, { rotation: structureRotation });
        }
        else {
            //mimic
            const mimic = dimension.spawnEntity("nps_tbe:mimic", block.bottomCenter());
            const yRotation = FakeChest.getYRotation(cardinalDirection);
            mimic.setRotation({ x: 0, y: yRotation });
        }
    }
    static getYRotation(cardinalDirection) {
        switch (cardinalDirection) {
            case Direction.North.toLowerCase(): return 180;
            case Direction.East.toLowerCase(): return 270;
            case Direction.South.toLowerCase(): return 0;
            case Direction.West.toLowerCase(): return 90;
            default: return 0;
        }
    }
    static getStructureRotation(cardinalDirection) {
        switch (cardinalDirection) {
            case Direction.North.toLowerCase(): return StructureRotation.None;
            case Direction.East.toLowerCase(): return StructureRotation.Rotate90;
            case Direction.South.toLowerCase(): return StructureRotation.Rotate180;
            case Direction.West.toLowerCase(): return StructureRotation.Rotate270;
            default: return StructureRotation.None;
        }
    }
}
FakeChest.componentName = "nps_tbe:32be9eef";
class SBK_01 {
    static initialize(event) { event.blockComponentRegistry.registerCustomComponent(this.componentName, new this()); }
    onTick(event) {
        const { block, dimension } = event;
        if (!SBK_01.shouldActivate(block, dimension))
            return;
        // 40% chance to destroy the block with no structure
        if (Math.random() < 0.4) {
            block.setType("minecraft:air");
            return;
        }
        const structureId = SBK_01.pickRandomStructure();
        const structure = world.structureManager.get(structureId);
        if (!structure)
            return;
        const direction = getCardinalDirection(block);
        const rotation = SBK_01.getRotation(direction);
        world.structureManager.place(structureId, dimension, block.location, { rotation });
    }
    static shouldActivate(block, dimension) {
        if (block.typeId != this.blockType)
            return false;
        const players = dimension.getEntities({
            type: "player",
            location: block.location,
            maxDistance: 64,
            excludeTags: [config.developerTag]
        });
        return players.length > 0;
    }
    static getRotation(direction) {
        const rotations = {
            north: StructureRotation.None,
            east: StructureRotation.Rotate90,
            south: StructureRotation.Rotate180,
            west: StructureRotation.Rotate270
        };
        return rotations[direction] ?? StructureRotation.None;
    }
    static pickRandomStructure() {
        const structures = [
            "mystructure:nps_tbe/enderchest",
            "mystructure:nps_tbe/mimic_feature",
            "mystructure:nps_tbe/sbk_01_pot",
            "mystructure:nps_tbe/sbk_01_barrel",
            "mystructure:nps_tbe/sbk_01_chest",
            "mystructure:nps_tbe/sbk_01_chest",
            "mystructure:nps_tbe/sbk_01_chest",
            "mystructure:nps_tbe/sbk_01_chest",
            "mystructure:nps_tbe/sbk_01_chest"
        ];
        return structures[getRandomInt(0, structures.length - 1)];
    }
}
//end tower
SBK_01.blockType = "nps_tbe:sbk_01";
SBK_01.componentName = "nps_tbe:a74e64f2";
class SBK_02 {
    static initialize(event) { event.blockComponentRegistry.registerCustomComponent(this.componentName, new this()); }
    onTick(event) {
        const { block, dimension } = event;
        if (!SBK_02.shouldActivate(block, dimension))
            return;
        // 40% chance to destroy the block with no structure
        if (Math.random() < 0.4) {
            block.setType("minecraft:air");
            return;
        }
        const structureId = SBK_02.pickRandomStructure();
        const structure = world.structureManager.get(structureId);
        if (!structure)
            return;
        const direction = getCardinalDirection(block);
        const rotation = SBK_02.getRotation(direction);
        world.structureManager.place(structureId, dimension, block.location, { rotation });
    }
    static shouldActivate(block, dimension) {
        if (block.typeId != this.blockType)
            return false;
        const players = dimension.getEntities({
            type: "player",
            location: block.location,
            maxDistance: 64,
            excludeTags: [config.developerTag]
        });
        return players.length > 0;
    }
    static getRotation(direction) {
        const rotations = {
            north: StructureRotation.None,
            east: StructureRotation.Rotate90,
            south: StructureRotation.Rotate180,
            west: StructureRotation.Rotate270
        };
        return rotations[direction] ?? StructureRotation.None;
    }
    static pickRandomStructure() {
        const structures = [
            "mystructure:nps_tbe/sbk_02_chest"
        ];
        return structures[getRandomInt(0, structures.length - 1)];
    }
}
//end pillar
SBK_02.blockType = "nps_tbe:sbk_02";
SBK_02.componentName = "nps_tbe:e3d343b8";
class ChorusFlare {
    static initialize(event) {
        event.blockComponentRegistry.registerCustomComponent(this.componentName, new this());
    }
    onTick(event) {
        const block = event.block;
        if (block.typeId == "nps_tbe:chorusflare_top") {
            const blockAbove = block.above();
            if (blockAbove == undefined)
                return;
            if (!blockAbove.isAir)
                return;
            const blockBelow = block.below();
            if (blockBelow == undefined)
                return;
            if (blockBelow.isAir)
                return;
            blockAbove.setType("nps_tbe:chorusflare_top");
            block.setType("nps_tbe:chorusflare_base");
        }
        else {
            const blockAbove = block.above();
            if (blockAbove == undefined)
                return;
            if (!blockAbove.isAir)
                return;
            const blockBelow = block.below();
            if (blockBelow == undefined)
                return;
            if (blockBelow.isAir)
                return;
            blockAbove.setType("nps_tbe:chorusflare_top");
            block.setType("nps_tbe:chorusflare_plant");
        }
    }
}
ChorusFlare.componentName = "nps_tbe:7d0efb4c";
world.beforeEvents.worldInitialize.subscribe(event => {
    ChorusFlare.initialize(event);
});
world.afterEvents.playerBreakBlock.subscribe(event => {
    const blockId = event.brokenBlockPermutation.type.id;
    const location = event.block.center();
    if (blockId == "minecraft:chorus_plant") {
        const commandString = `/loot spawn ${location.x} ${location.y} ${location.z} loot "nps/tbe/gameplay/on_chorus_destroy"`;
        event.dimension.runCommand(commandString);
    }
});
system.runInterval(() => {
    world.getAllPlayers().forEach(player => {
        try {
            const playerBlock = player.dimension.getBlock(player.location);
            if (playerBlock == undefined)
                return;
            if (!playerBlock.getTags().includes("nps_tbe:magic_bean"))
                return;
            if (player.isJumping) {
                player.addEffect("levitation", 20, { showParticles: false, amplifier: 6 });
                player.removeEffect("slow_falling");
            }
            else {
                player.addEffect("slow_falling", 20, { showParticles: false });
                player.removeEffect("levitation");
            }
        }
        catch {
            return;
        }
    });
}, 10);
