import { Block, Dimension, ItemComponentUseOnEvent, StructureRotation, world } from "@minecraft/server";
import { REPLACEABLE_BLOCKS } from "../@minecraft/ReplaceableBlocks";
import { Helper } from "../utils/Helper";
import { Vec3 } from "../utils/Vec3";
export class QueenAnt {
  constructor() {
    this.updatedReplaceableBlocks = [...REPLACEABLE_BLOCKS, "sf_nba:ant_hill", "sf_nba:ant_hill_base"];
    this.onUseOn = this.onUseOn.bind(this);
  }
  onUseOn({ source, block, faceLocation }) {
    const { dimension } = source;
    const placePos = !this.updatedReplaceableBlocks.includes(block.typeId) ? block.above().location : block.location;
    const validateArea = this.#isValidPlace(dimension, placePos);
    if (!validateArea.isValidArea) {
      for (const invalidBlock of validateArea.blockingBlocks) {
        const particlePos = Vec3.add(invalidBlock.location, new Vec3(0.5, 0.5, 0.5));
        dimension.spawnParticle("sf_nba:ant_block_indicator", particlePos);
      }
      return;
    }
    const posOffset = Vec3.add(placePos, new Vec3(-1, 0, -1));
    const rotations = Object.values(StructureRotation);
    Helper.decreaseMainhandItemStack(source);
    world.structureManager.place("sf_nba:ant_hill_small", dimension, posOffset, {
      rotation: rotations[Math.floor(Math.random() * rotations.length)]
    });
  }
  #isValidPlace(dimension, location) {
    const aabb = this.#getAABBFromClickedBlock(location);
    const blockingBlocks = [];
    for (let x = aabb.min.x; x <= aabb.max.x; x++) {
      for (let y = aabb.min.y; y <= aabb.max.y; y++) {
        for (let z = aabb.min.z; z <= aabb.max.z; z++) {
          const block = dimension.getBlock({ x, y, z });
          if (block && (!block.isAir && !this.updatedReplaceableBlocks.includes(block.typeId))) {
            blockingBlocks.push(block);
          }
        }
      }
    }
    return {
      isValidArea: blockingBlocks.length === 0,
      blockingBlocks
    };
  }
  #getAABBFromClickedBlock(location) {
    const pos1 = Vec3.add(location, new Vec3(1, 0, 1));
    const pos2 = Vec3.add(location, new Vec3(-1, 2, -1));
    const min = new Vec3(Math.min(pos1.x, pos2.x), Math.min(pos1.y, pos2.y), Math.min(pos1.z, pos2.z));
    const max = new Vec3(Math.max(pos1.x, pos2.x), Math.max(pos1.y, pos2.y), Math.max(pos1.z, pos2.z));
    return { min, max };
  }
}