import { world, system, BlockPermutation, GameMode } from "@minecraft/server";

world.beforeEvents.worldInitialize.subscribe(initEvent => {
  initEvent.blockTypeRegistry.registerCustomComponent("nicothekid:artifacture_table_activation", {
    onPlayerInteract: eventData => {
      const player = eventData.player;
      const block = eventData.block;
      const blockLocation = block.location;
      const playerEquippable = player.getComponent("equippable");
      const itemUsed = playerEquippable.getEquipment("Mainhand");
      function decreaseItem () {
        system.run(() => {
          if (!player.matches({ gameMode: GameMode.creative })) {
            const decrementItem = itemUsed.amount == 1 ? undefined : (itemUsed.amount--, itemUsed);
            playerEquippable.setEquipment("Mainhand", decrementItem)
          }
        });
      }
      if (player.isSneaking) return;
      if (block.permutation.matches("nicothekid:artifacture_table", { "nicothekid:artifacture_table_active": false })) {
        if (itemUsed === undefined) {
          player.playSound("game.player.attack.nodamage", { pitch: 1.1, location: player.location, volume: 1.0 });
          player.runCommandAsync(`tellraw @p {\"rawtext\":[{\"text\":\"§eYou must have an Amethyst Shard in your hand to activate the Artifacture Table.§r\"}]}`);
          return;
        }
        else if (itemUsed.typeId === "minecraft:amethyst_shard") {
          decreaseItem ();
          block.dimension.playSound("respawn_anchor.charge", blockLocation, { pitch: 1.1, volume: 1.0 });
          block.dimension.spawnParticle("nicothekid:artifacture_table_particle", { x: blockLocation.x + 0.5, y: blockLocation.y + 0.5, z: blockLocation.z + 0.5 });
          block.setPermutation(BlockPermutation.resolve("nicothekid:artifacture_table", { "nicothekid:artifacture_table_active": true }));
          return;
        }
        else return;
      }
      else return;
    }
  });
  initEvent.blockTypeRegistry.registerCustomComponent("nicothekid:artifacture_table_deactivation", {
    onTick: eventData => {
      const block = eventData.block;
      const blockLocation = block.location;
      if (block.permutation.matches("nicothekid:artifacture_table", { "nicothekid:artifacture_table_active": true })) {
        block.dimension.playSound("break.amethyst_block", blockLocation, { pitch: 1.1, volume: 1.0 });
        block.setPermutation(BlockPermutation.resolve("nicothekid:artifacture_table", { "nicothekid:artifacture_table_active": false }));
        return;
      }
      else return;
    }
  });
});