import { BlockVolume, Dimension, Entity, system } from "@minecraft/server";
import { Vec3 } from "../utils/Vec3";
import { AntHillBlock } from "../block/AntHillBlock";
const ON_REACH_ANT_HILL_EVENT_ID = "sf_nba:ant_reached_ant_hill";
export class Ant {
  constructor() {
    system.run(() => {
      this.onReachAntHill();
    });
  }
  onReachAntHill() {
    system.afterEvents.scriptEventReceive.subscribe(({ id, sourceEntity: ant }) => {
      if (id !== ON_REACH_ANT_HILL_EVENT_ID) return;
      if (!ant) return;
      const { location: pos, dimension } = ant;
      const blockLocation = this.#getClosestAntHillBlockLocation(dimension, pos);
      if (!blockLocation) {
        this.#addFindAntHillTimeoutTo(ant);
        return;
      };
      const block = dimension.getBlock(blockLocation);
      if (!block || block.typeId !== "sf_nba:ant_hill") {
        this.#addFindAntHillTimeoutTo(ant);
        return;
      };
      const workersState = block.permutation.getState(AntHillBlock.WORKERS_STATE);
      if (workersState >= AntHillBlock.MAX_WORKERS) {
        this.#addFindAntHillTimeoutTo(ant);
        return;
      }
      dimension.playSound("sf_nba.ant_hill.enterleave", blockLocation);
      dimension.spawnParticle("sf_nba:generic_poof", blockLocation);
      block.setPermutation(block.permutation.withState(AntHillBlock.WORKERS_STATE, workersState + 1));
      ant.remove();
    });
  }
  #addFindAntHillTimeoutTo(entity) {
    entity.triggerEvent("sf_nba:ant_find_ant_hill_timeout");
  }
  #getClosestAntHillBlockLocation(dimension, location) {
    const volume = Vec3.fromMinecraftVector3(location).toBlockVolume(1);
    const blocks = dimension.getBlocks(volume, { includeTypes: ["sf_nba:ant_hill"] });
    let block = null;
    let minDistance = Infinity;
    for (const iBlock of blocks.getBlockLocationIterator()) {
      const distance = Math.sqrt(
        Math.pow(iBlock.x - location.x, 2) +
        Math.pow(iBlock.y - location.y, 2) +
        Math.pow(iBlock.z - location.z, 2)
      );
      if (distance < minDistance) {
        minDistance = distance;
        block = iBlock;
      }
    }
    return block;
  }
}
new Ant();