import { world, system } from "@minecraft/server";
import { getMacro, isMacroEnabled } from "../util/macro_utils";
world.afterEvents.playerPlaceBlock.subscribe((placeJigsaw)=>{
    if (placeJigsaw.block.typeId != "jigsaw:jigsaw_block") return;
    const block = placeJigsaw.block;
    const permutation = block.permutation;
    // player placed flag
    let playerPlacedJigsaws = world.getDynamicProperty("jigsaw:player_placed");
    if (playerPlacedJigsaws == undefined) {
        world.setDynamicProperty("jigsaw:player_placed", "[]");
    }
    playerPlacedJigsaws = JSON.parse(world.getDynamicProperty("jigsaw:player_placed"));
    playerPlacedJigsaws.push(placeJigsaw.block.location);
    world.setDynamicProperty("jigsaw:player_placed", JSON.stringify(playerPlacedJigsaws));
    ///
    const dimension = placeJigsaw.dimension;
    const dataEntity = dimension.spawnEntity("jigsaw:jigsaw_data", {
        x: placeJigsaw.block.location.x + 0.5,
        y: placeJigsaw.block.location.y + 0.5,
        z: placeJigsaw.block.location.z + 0.5
    });
    const blockData = {
        targetPool: "minecraft:empty",
        name: "minecraft:empty",
        targetName: "minecraft:empty",
        turnsInto: "minecraft:air",
        jointType: "rollable",
        placementPriority: 0,
        selectionPriority: 0,
        levels: 20,
        level: 0,
        cardinalDirection: permutation.getState("minecraft:cardinal_direction"),
        blockFace: permutation.getState("minecraft:block_face"),
        branch: false
    };
    const macro = getMacro(placeJigsaw.player);
    if (macro && isMacroEnabled(placeJigsaw.player)) {
        blockData.targetPool = macro.targetPool;
        blockData.name = macro.name;
        blockData.targetName = macro.targetName;
        blockData.turnsInto = macro.turnsInto;
        blockData.jointType = macro.jointType;
        blockData.placementPriority = macro.placementPriority;
        blockData.selectionPriority = macro.selectionPriority;
    }
    dataEntity.setDynamicProperty("jigsawData", JSON.stringify(blockData));
});
world.beforeEvents.playerBreakBlock.subscribe((breakJigsaw)=>{
    if (breakJigsaw.block.typeId != "jigsaw:jigsaw_block") return;
    const playerPlacedJigsaws = JSON.parse(world.getDynamicProperty("jigsaw:player_placed"));
    try {
        playerPlacedJigsaws.splice(playerPlacedJigsaws.indexOf(breakJigsaw.block.location), 1);
    } catch  {
        console.warn("§dJigsaw Block Bedrock§r (§4Error§r): Failed to remove player placed jigsaw data");
    }
    const dimension = breakJigsaw.dimension;
    const dataEntity = dimension.getEntitiesAtBlockLocation(breakJigsaw.block.location)[0];
    if (dataEntity == undefined) return;
    system.run(()=>{
        dataEntity.remove();
    });
});
