import { Player, Block, Entity, ItemStack, world } from "@minecraft/server";
import { pistonsConfig } from "./config";

class BlockUtils {
  /**
   * @param {Player} player
   * @param {Block} block
   * @param {ItemStack} item
   */
  constructor(block, player, item) {
    this.block = block;
    this.blockid = block?.typeId;
    this.blockLoc = block?.location;
    this.blockDim = block?.dimension;
    this.player = player;
    this.playerLoc = player?.location;
    this.playerDim = player?.dimension;
    this.item = item;
    this.itemid = item?.typeId;
  }

  scbSpawnEntity(id, yOffset = 0) {
    const entity = this.blockDim?.spawnEntity(id, {
      x: this.blockLoc.x + 0.5,
      y: this.blockLoc.y + yOffset,
      z: this.blockLoc.z + 0.5,
    });
    this.player
      ? (entity.nameTag = `${this.player.name}'s Property`)
      : "SecurityCraft";
    return entity;
  }
  /**
   * @param {Entity} entity
   */
  scbSetTamed(entity) {
    const tameable = entity?.getComponent("tameable");
    tameable?.tame(this.player);
  }
  // Place @Event
  bigReinforcedChestKeypadOnPlaced() {
    if (this.blockid !== "scb:big_reinforced_chest_keypad") return;
    this.scbSpawnEntity("scb:big_reinforced_chest_keypad");
  }
  bigReinforcedChestOnPlaced() {
    if (this.blockid !== "scb:big_reinforced_chest") return;
    const chest = this.scbSpawnEntity("scb:big_reinforced_chest");
    this.scbSetTamed(chest);
  }
  reinforcedChestKeypadOnPlaced() {
    if (this.blockid !== "scb:reinforced_chest_keypad") return;
    this.scbSpawnEntity("scb:reinforced_chest_keypad");
  }
  reinforcedChestOnPlaced() {
    if (this.blockid !== "scb:reinforced_chest") return;
    const chest = this.scbSpawnEntity("scb:reinforced_chest");
    this.scbSetTamed(chest);
  }
  keyPadOnPlaced() {
    if (!this.blockid.includes("keypad_block")) return;
    this.scbSpawnEntity("scb:keypad_entity");
  }
  mineOnPlaced() {
    if (!this.blockid.includes("mine_inactive")) return;
    this.scbSpawnEntity("scb:mine_entity");
  }
  cameraOnPlaced() {
    if (!this.blockid.includes("camera")) return;
    this.scbSpawnEntity("scb:camera_entity");
  }
  scannerOnPlaced() {
    if (!this.blockid.includes("scanner")) return;
    const scanner = this.scbSpawnEntity("scb:scanner");
    scanner.addTag("scanner:" + this.player.name);
    this.scbSetTamed(scanner);
    scanner.triggerEvent("tamed");
  }
  turretOnPlaced() {
    if (!this.itemid.includes("turret")) return;
    const turret = this.scbSpawnEntity("scb:turret", 1);
    this.scbSetTamed(turret);
    turret.addTag(`owner:${this.player.name}`);
    turret.nameTag = "";
  }
  reinforcedDoorOnPlaced() {
    if (!this.blockid.includes("reinforced_door")) return;
    const door = this.scbSpawnEntity("scb:scanner_door");
    door.addTag(`owner:${this.player.name}`);
  }
  removePiston() {
    if (!this.blockid.includes("piston")) return;
    if (!pistonsConfig.active) return;
    const distance = pistonsConfig.distance;

    let itemSpawned = false; // Bandera para rastrear si ya hemos generado el item

    for (let x = -distance; x <= distance && !itemSpawned; x++) {
      for (let y = -distance; y <= distance && !itemSpawned; y++) {
        for (let z = -distance; z <= distance && !itemSpawned; z++) {
          const currentLocation = {
            x: this.blockLoc.x + x,
            y: this.blockLoc.y + y,
            z: this.blockLoc.z + z,
          };

          const block = this.block.dimension.getBlock(currentLocation);
          const reinforced = world
            .getDynamicPropertyIds()
            .find((e) =>
              e.includes(
                `${currentLocation.x} ${currentLocation.y} ${currentLocation.z}`
              )
            );

          if (reinforced === "" || reinforced === undefined) continue;

          // Genera el item solo una vez
          this.block.dimension.spawnItem(
            new ItemStack(this.blockid),
            this.blockLoc
          );
          this.block.setType("minecraft:air");

          itemSpawned = true; // Marca que hemos generado el item
        }
      }
    }
  }

  // Step @Event
  mineOnStep() {
    if (!this.blockid.includes("mine_active")) return;
    this.blockDim
      .getEntities({
        location: this.blockLoc,
        type: "scb:mine_entity",
        maxDistance: 1,
        closest: 1,
      })[0]
      ?.remove();
    this.blockDim.setBlockType(this.blockLoc, "minecraft:air");
    this.blockDim.createExplosion(this.blockLoc, 4, {
      allowUnderwater: false,
      causesFire: true,
      breaksBlocks: true,
    });
  }
}

export default BlockUtils;
