import { world, SoundOptions } from "mojang-minecraft";
import { ActionFormData } from "mojang-minecraft-ui";
import { mobs } from "scripts/morphables.js";

world.events.itemDefinitionEvent.subscribe(data => {
  const { eventName, source } = data;

  if (eventName == "morph:morphing_bracelet") {
    let morph_menu = new ActionFormData();
    let on_click = [];
  
    morph_menu.title("Morph Menu");
    morph_menu.body("Pick a mob to morph!");

    for(let i = 0; i < mobs.length; i++) {  
      if (source.hasTag(mobs[i].id) && !(source.getComponent("minecraft:variant").value == mobs[i].variant && new Function("source", "return " + mobs[i].condition.toString().replace(/entity/g, "source"))(source))) {
        morph_menu.button(mobs[i].name, `textures/icons/${mobs[i].entity.split(":")[1]}/${mobs[i].id.split(":")[1]}`);
        on_click.push(mobs[i].id);
      };
    };

    if (on_click.length > 0) {
      morph_menu.show(source).then(actionFormResponse => {
        const { isCancelled, selection } = actionFormResponse;
        if (!isCancelled) {
          source.triggerEvent(on_click[selection]);
        };
      });
    } else {
      morph_menu.button("Close");
      morph_menu.show(source);
    };
  };
});

world.events.entityHit.subscribe(data => {
  const { entity, hitEntity, hitBlock } = data;

  if ((hitEntity && !hitBlock) && entity.id == 'minecraft:player' && hitEntity.getComponent("minecraft:health") != undefined && hitEntity.getComponent("minecraft:health").current <= 0) {
    for(let i = 0; i < mobs.length; i++) { 
      try {
        if (entity.runCommand(`testfor @s[hasitem={item=morph:morphing_bracelet}]`) && !entity.hasTag(mobs[i].id) && (hitEntity.id == mobs[i].entity && new Function("hitEntity", "return " + mobs[i].condition.toString().replace(/entity/g, "hitEntity"))(hitEntity))) {
          entity.addTag(mobs[i].id);
          let sound_options = new SoundOptions(); sound_options.location = entity.location;
          world.playSound("beacon.activate", sound_options);
        };
      } catch {};
    };
  };
});

world.events.tick.subscribe(data => {
  for(const player of Array.from(world.getPlayers())){
    for(let i = 0; i < mobs.length; i++) { 
  
      if ((player.getComponent("minecraft:variant").value == mobs[i].variant && new Function("player", "return " + mobs[i].condition.toString().replace(/entity/g, "player"))(player)) && !player.hasTag(mobs[i].id)) {
        player.addTag(mobs[i].id);
      };
    };
  };
});