import { world, system, ItemStack, EquipmentSlot, GameMode, BlockPermutation } from "@minecraft/server";
import { calculateKnockbackVector } from "../utilities/knockbacks";

// Sound constants for spawner events.
const SOUND_SPAWN_WAVE = "trial_spawner.spawn_mob";
const SOUND_AMBIENT = "trial_spawner.ambient";

export function facelessVindicatorHit() {
  world.afterEvents.entityHitEntity.subscribe((event) => {
    const damager = event.damagingEntity;
    const hit_entity = event.hitEntity;
    if (!hit_entity || !hit_entity.isValid());
    if (!damager || !damager.isValid());
    if (damager.typeId != "hb_hr:faceless_vindicator" && hit_entity.typeId != "player") return;
    try {
      const kbVector = calculateKnockbackVector(hit_entity.location, damager.location, 1);
      hit_entity.applyKnockback(kbVector.x, kbVector.z, 2.75, 0.5);
    } catch (error) {}
  });
}
export function facelessPillagerMediumHit() {
  world.afterEvents.entityHitEntity.subscribe((event) => {
    const damager = event.damagingEntity;
    const hit_entity = event.hitEntity;
    if (!hit_entity || !hit_entity.isValid());
    if (!damager || !damager.isValid());
    if (damager.typeId != "hb_hr:faceless_pillager_medium" && hit_entity.typeId != "player") return;
    try {
      hit_entity?.addEffect("minecraft:slowness", Math.random() < 0.5 ? 20 : 40, { amplifier: 0, showparticles: false });
    } catch (error) {}
  });
}

export function facelessSpawner() {
  // Register the custom block component for the grass plant.
  // This allows the block to react to bonemeal usage.
  world.beforeEvents.worldInitialize.subscribe((event) => {
    event.blockComponentRegistry.registerCustomComponent("hb_hr:faceless_spawner", {
      // Optionally, handle natural growth in onRandomTick.
      onTick(data) {
        const block = data.block;
        try {
          block.dimension.spawnParticle("hb_hr:faceless_spawner_flame", block.center());

          if (Math.random() < 0.33) {
            block.dimension.playSound(SOUND_AMBIENT, block.center());
          }
        } catch (error) {}

        let nearbyLostSouls = world.getDimension(block.dimension.id).getEntities({
          location: block.center(),
          excludeTags: ["hb_hr:testing"],
          type: "minecraft:player",
          maxDistance: 3,
        });
        if (nearbyLostSouls.length === 0 || nearbyLostSouls[0] == undefined) {
          return;
        } else {
          block.dimension.spawnParticle("hb_hr:faceless_spawner_spawner_spawn", {
            x: block.center().x,
            y: block.center().y - 0.4,
            z: block.center().z,
          });
          block.dimension.playSound(SOUND_SPAWN_WAVE, block.location);
          const minAmount = 1;
          const maxAmount = 3;
          // Calculate a random number between minAmount and maxAmount (inclusive)
          const amount = Math.floor(Math.random() * (maxAmount - minAmount + 1)) + minAmount;

          // your four custom entity IDs
          const entityTypes = ["hb_hr:faceless_pillager_small", "hb_hr:faceless_pillager_medium", "hb_hr:faceless_pillager_large", "hb_hr:faceless_vindicator"];
          // TODO: add the other pillagers later they arent created yet
          // const entityTypes = ["hb_hr:faceless_pillager_small", "hb_hr:faceless_pillager_medium", "hb_hr:faceless_pillager_large", "hb_hr:faceless_vindicator"];

          for (let i = 0; i < amount; i++) {
            // pick random type
            const type = entityTypes[Math.floor(Math.random() * entityTypes.length)];

            // pick a magnitude in [0.5, 1]
            const magX = 0.5 + Math.random() * 0.5;
            const magZ = 0.5 + Math.random() * 0.5;

            // randomly flip sign to get into [-1, -0.5] or [0.5, 1]
            const offsetX = Math.random() < 0.5 ? -magX : magX;
            const offsetZ = Math.random() < 0.5 ? -magZ : magZ;

            // build a new spawn position
            const spawnPos = {
              x: block.center().x + offsetX,
              y: block.center().y - 0.5,
              z: block.center().z + offsetZ,
            };
            const spawnedEntity = block.dimension.spawnEntity(type, spawnPos);

            block.dimension.spawnParticle("hb_hr:faceless_spawner_spawner_spawn", spawnedEntity.location);
            system.waitTicks(10);
          }

          block.dimension.runCommand("/fill " + block.location.x + " " + block.location.y + " " + block.location.z + " " + block.location.x + " " + block.location.y + " " + block.location.z + " air destroy");
        }
      },
    });
  });
}
