import * as mc from "@minecraft/server";
import { SafetyCheckedEntity, Vector3, mclog } from "./utils/index";
export function initWeaponPoster() {
    // Replace currently existing poster entities with block when they load
    mc.system.afterEvents.scriptEventReceive.subscribe(event => {
        if (event.id === "ldz:weapon_poster_on_load" && event.sourceEntity && event.sourceEntity.typeId === "ldz:poster_weapon") {
            replacePosterEntityWithBlock(new SafetyCheckedEntity(event.sourceEntity));
        }
    });
    // Remove poster spawner entity on spawn
    mc.world.afterEvents.entitySpawn.subscribe(event => {
        if (event.entity.typeId.includes("ldz:poster_spawner")) {
            event.entity.remove();
        }
    });
    // Trigger poster placement when spawn egg item used
    mc.world.afterEvents.itemUseOn.subscribe(event => {
        if (event.itemStack.typeId.includes("ldz:poster_spawner")) {
            onPosterSpawnEggUsed(event);
        }
    });
    // Remove effects from key entities
    mc.world.afterEvents.effectAdd.subscribe(event => {
        if (event.entity.typeId === "ldz:poster_weapon" || event.entity.typeId.includes("poster_spawner"))
            event.entity.removeEffect(event.effect.typeId);
    });
}
function replacePosterEntityWithBlock(poster) {
    var _a, _b, _c, _d;
    if (!poster.isValid())
        return;
    const posterBlockFace = [mc.Direction.South, mc.Direction.South, mc.Direction.West, mc.Direction.North, mc.Direction.East][(_b = (_a = poster.getComponent(mc.EntityVariantComponent.componentId)) === null || _a === void 0 ? void 0 : _a.value) !== null && _b !== void 0 ? _b : 0];
    const posterCardinalDirection = posterBlockFace;
    const posterSkinId = (_d = (_c = poster.getComponent(mc.EntitySkinIdComponent.componentId)) === null || _c === void 0 ? void 0 : _c.value) !== null && _d !== void 0 ? _d : 0;
    const posterMob = POSTER_SKIN_ID_MOB_LIST[posterSkinId];
    mclog(`Replacing ${posterMob} poster entity with block @ ${poster.location}`);
    spawnPosterAsBlock(poster.dimension, posterMob, poster.location, posterBlockFace, posterCardinalDirection);
    poster.remove();
}
function onPosterSpawnEggUsed(event) {
    const player = event.source;
    const dimension = player.dimension;
    const posterSpawnEggItem = event.itemStack;
    const mobName = posterSpawnEggItem.typeId.replace(/ldz:poster_spawner_(\w+)_spawn_egg/, "$1");
    const onBlock = event.block;
    let blockFace = event.blockFace;
    let posterBlockLocation;
    switch (blockFace) {
        case mc.Direction.Up:
            posterBlockLocation = new Vector3(onBlock.location).up();
            break;
        case mc.Direction.Down:
            posterBlockLocation = new Vector3(onBlock.location).down();
            break;
        case mc.Direction.North:
            posterBlockLocation = new Vector3(onBlock.location).north();
            break;
        case mc.Direction.South:
            posterBlockLocation = new Vector3(onBlock.location).south();
            break;
        case mc.Direction.East:
            posterBlockLocation = new Vector3(onBlock.location).east();
            break;
        case mc.Direction.West:
            posterBlockLocation = new Vector3(onBlock.location).west();
            break;
    }
    if (player.hasTag("dev"))
        dimension.spawnParticle("minecraft:endrod", posterBlockLocation.center());
    const posterBlock = dimension.getBlock(posterBlockLocation);
    if (onBlock.isAir || (!posterBlock || !posterBlock.isValid() || !posterBlock.isAir)) {
        if (!player.matches({ gameMode: mc.GameMode.creative }))
            dropPoster(dimension, posterBlockLocation, mobName);
        return;
    }
    let cardinalDirection;
    const yRotation = event.source.getRotation().y;
    if (yRotation > -135 && yRotation <= -45)
        cardinalDirection = mc.Direction.East;
    else if (yRotation > -45 && yRotation <= 45)
        cardinalDirection = mc.Direction.South;
    else if (yRotation > 45 && yRotation <= 135)
        cardinalDirection = mc.Direction.West;
    else
        cardinalDirection = mc.Direction.North;
    spawnPosterAsBlock(dimension, mobName, posterBlockLocation, blockFace, cardinalDirection);
}
function dropPoster(dimension, location, mobName) {
    // dimension.runCommand(`setblock ${location} air`);
    dimension.runCommand(`loot spawn ${location} loot \"posters/${mobName}_weapon\"`);
    dimension.getEntities({ type: "minecraft:item", location: location, maxDistance: 1 }).forEach(item => item.teleport(location.center(), { keepVelocity: true }));
}
/**
 * @deprecated Only made for dev. {@link spawnPosterAsBlock} is the expected use.
 */
function spawnPosterAsEntity(dimension, location, mobName, direction) {
    const poster = dimension.spawnEntity(`ldz:poster_weapon`, location);
    poster.triggerEvent(mobName);
    switch (direction) {
        case mc.Direction.North:
            poster.triggerEvent("north");
            break;
        case mc.Direction.South:
            poster.triggerEvent("south");
            break;
        case mc.Direction.East:
            poster.triggerEvent("east");
            break;
        case mc.Direction.West:
            poster.triggerEvent("west");
            break;
    }
}
function spawnPosterAsBlock(dimension, mobName, location, blockFace, cardinalDirection) {
    const blockString = `ldz:${mobName}_weapon_poster["minecraft:block_face"="${blockFace.toLowerCase()}", "minecraft:cardinal_direction"="${cardinalDirection.toLowerCase()}"]`;
    mclog(`Setting block ${blockString}`);
    dimension.runCommand(`setblock ${location} ${blockString}`);
}
const POSTER_SKIN_ID_MOB_LIST = [
    "axolotl",
    "axolotl",
    "bat",
    "bee",
    "blaze",
    "cat",
    "cave_spider",
    "chicken",
    "cod",
    "cow",
    "creeper",
    "dolphin",
    "donkey",
    "drowned",
    "elder_guardian",
    "ender_dragon",
    "enderman",
    "endermite",
    "evoker",
    "fox",
    "ghast",
    "glow_squid",
    "goat",
    "guardian",
    "hoglin",
    "horse",
    "husk",
    "iron_golem",
    "llama",
    "magma_cube",
    "mooshroom",
    "mule",
    "ocelot",
    "panda",
    "parrot",
    "phantom",
    "pig",
    "piglin",
    "piglin_brute",
    "pillager",
    "polar_bear",
    "pufferfish",
    "rabbit",
    "ravager",
    "salmon",
    "sheep",
    "shulker",
    "silverfish",
    "skeleton",
    "skeleton_horse",
    "slime",
    "snow_golem",
    "spider",
    "squid",
    "stray",
    "strider",
    "tropical_fish",
    "turtle",
    "vex",
    "villager",
    "vindicator",
    "wandering_trader",
    "witch",
    "wither",
    "wither_skeleton",
    "wolf",
    "zoglin",
    "zombie",
    "zombie_piglin",
    "zombie_villager",
    // 1.19
    "allay",
    "frog",
    "tadpole",
    "warden",
    // 1.20
    "camel",
    "sniffer",
    "armadillo",
    // 1.21
    "bogged",
    "breeze",
];
