import { BlockPermutation, world } from "@minecraft/server";
import { ActionFormData  } from "@minecraft/server-ui";

world.beforeEvents.worldInitialize.subscribe(ev => {
  ev.blockComponentRegistry.registerCustomComponent("yog:galvan_pod_loot", {
    onPlayerInteract(event) {
      const { block } = event;

      const states = block.permutation.getAllStates();
      if (states["yog:is_empty"]) {
        return;
      }

      block.dimension.runCommand(
        `loot spawn ${block.x + 0} ${block.y + 1} ${block.z + 0} loot "blocks/galvan_pod"`
      );

      try {
        const newPerm = BlockPermutation.resolve(block.typeId, {
          ...states,
          "yog:is_empty": true
        });
        block.setPermutation(newPerm);
      } catch {}

      world.playSound("gas_hissing", block.location, { pitch: 1 });
    }
  });
  ev.blockComponentRegistry.registerCustomComponent("yog:dna_maker", {
    onPlayerInteract(event) {
      const player = event.player;

      let form = new ActionFormData()
        .title("DNA - Maker")
        .body("Other's alien DNA coming soon.")
        .button(`Alien-X DNA`, `textures/ui/_yog/alien_x_dna_maker`);

      form.show(player).then(res => {
        if (res.canceled) {
          return;
        }

        if (res.selection === 0) {
          player.runCommandAsync(`function blocks/dna_maker`);
        }
      });
    }
  });
});
