import { world, Vector, MinecraftEffectTypes, SoundOptions } from "mojang-minecraft";

world.events.entityHit.subscribe(data => {
  const { entity, hitEntity, hitBlock } = data;
  if ((hitEntity && !hitBlock) && entity.id == "minecraft:player" && !hitEntity.hasTag("damaged")) {
    damaged_tag(hitEntity);

    if (entity.getComponent("minecraft:variant").value == 15) {
      hitEntity.addEffect(MinecraftEffectTypes.wither, 10 * 20, 0);
    };
    if (entity.getComponent("minecraft:variant").value == 19) {
      hitEntity.addEffect(MinecraftEffectTypes.hunger, 30 * 20, 0);
    };
    if (entity.getComponent("minecraft:variant").value == 23) {
      hitEntity.setVelocity(new Vector(hitEntity.velocity.x * 1.5, hitEntity.velocity.y * 3.5, hitEntity.velocity.z * 1.5));
    };
    if (entity.getComponent("minecraft:variant").value == 33) {
      hitEntity.addEffect(MinecraftEffectTypes.poison, 7 * 20, 0);
    };
    if (entity.getComponent("minecraft:variant").value == 40 && entity.getComponent("minecraft:mark_variant").value != 1) {
      hitEntity.addEffect(MinecraftEffectTypes.poison, 10 * 20, 0);

      try {
        if (entity.runCommand("testfor @s[m=!1]")) {
          entity.triggerEvent("morph:bee_countdown_to_perish");
          let sting_sound = new SoundOptions(); sting_sound.location = entity.location;
          world.playSound("mob.bee.sting", sting_sound);
        };
      } catch {};
    };
  };
});

function damaged_tag(entity) {
  entity.addTag("damaged");
  let duration = 10;
  let end = () => {
    duration = duration - 1;
    if (duration <= 0) {
      try {
        entity.removeTag("damaged");
      } catch {};
      world.events.tick.unsubscribe(end);
    };
  };
  world.events.tick.subscribe(end);
};