import { BlockPermutation, ItemStack } from "@minecraft/server";
import { gamerules, beforeEvents } from "./eternal/constants";

/** @type {import("@minecraft/server").BlockCustomComponent} */
const doubplePlantComponent = {
  //WHEN PLACING THE BLOCK
  beforeOnPlayerPlace(event) {
    const { block, player } = event;

    if (block.above()?.typeId === "minecraft:air") {
      const equipment = player.getComponent("equippable");
      const selectedItem = equipment.getEquipment("Mainhand");

      event.permutationToPlace = event.permutationToPlace.withState("ecbl_bc:upper_block_bit", false);

      block.above().setPermutation(
        BlockPermutation.resolve(selectedItem.typeId, {
          "ecbl_bc:upper_block_bit": true,
        })
      );
    } else event.cancel = true;
  },

  onPlayerDestroy(event) {
    const { block, destroyedBlockPermutation, dimension, player } = event;
    const blockUpperState = destroyedBlockPermutation.getState("ecbl_bc:upper_block_bit");

    //check if each door destroyed
    if (blockUpperState) block.below().setType("minecraft:air");
    else block.above().setType("minecraft:air");

    if (player.gamemode !== "creative" && gamerules.doTileDrops)
      dimension.spawnItem(new ItemStack(destroyedBlockPermutation.type.id), block.location);
  },

  onTick(event) {
    const { block, dimension } = event;
    const blockUpperState = block.permutation.getState("ecbl_bc:upper_block_bit");
    const typeId = block.typeId;

    if (blockUpperState === false && block.below()?.typeId === "minecraft:air") {
      block.setType("minecraft:air");
      block.above()?.setType("minecraft:air");
      if (gamerules.doTileDrops) dimension.spawnItem(new ItemStack(typeId), block.location);
    }
  },
};

const animationUse = {
  beforeOnPlayerPlace(event) {
    const { block, player } = event;

    if (block.above()?.typeId === "minecraft:air") {
      player.runCommandAsync('testfor @s');
    }
  }
}


beforeEvents.worldInitialize.subscribe(({ blockComponentRegistry }) => {
  blockComponentRegistry.registerCustomComponent("ecbl_bc:double_plant", doubplePlantComponent);
});

beforeEvents.worldInitialize.subscribe(({ blockComponentRegistry }) => {
  blockComponentRegistry.registerCustomComponent("ecbl_bc:animation_use", animationUse);
});
