import { system, world, BlockVolume, BlockPermutation } from "@minecraft/server";
import { breakVines, vineCheckBlockBelow, vineClimbMechanic } from "./block_handler";

export function hiveBlockTick(player) {
  if (system.currentTick % 5 != 0) return;
  const volume = new BlockVolume({ x: player.location.x + 5, y: player.location.y + 5, z: player.location.z + 5 }, { x: player.location.x - 5, y: player.location.y - 5, z: player.location.z - 5 });

  const locations = volume.getBlockLocationIterator();

  for (const location of locations) {
    const block = player.dimension.getBlock(location);
    if (!block) continue;
    if (!block.typeId.includes("hb_hr:") && !block.typeId.includes("hive")) continue;

    // Get the center and origin of the block
    switch (block.typeId) {
      case "hb_hr:hive_vine":
        if (system.currentTick % 20 == 0) {
          vineCheckBlockBelow(block);
        }
        vineClimbMechanic(block);
      case "hb_hr:small_hive_egg":
      case "hb_hr:hive_vine":
        runIntoSmallDeathMothEggs(block);
        break;
    }
  }
}

export function spawnDeathMothFromLargeEgg(block, minAmount, maxAmount) {
  // Calculate a random number between minAmount and maxAmount (inclusive)
  const amount = Math.floor(Math.random() * (maxAmount - minAmount + 1)) + minAmount;

  // Loop to spawn the calculated amount of Death Moths
  for (let i = 0; i < amount; i++) {
    // Assumes there is a method world.spawnEntity that takes the entity type, spawn location, and player as parameters.
    block.dimension.spawnEntity("hb_hr:death_moth", block.location);
    block.dimension.spawnParticle("hb_hr:death_moth_spawn_dust", block.center());
    block.dimension.spawnParticle("hb_hr:death_moth_spawn", block.center());
  }

  block.dimension.runCommand("/fill " + block.location.x + " " + block.location.y + " " + block.location.z + " " + block.location.x + " " + block.location.y + " " + block.location.z + " air destroy");
  // Send a message indicating how many Death Moths were spawned
  // world.sendMessage(amount + " Death Moths have been spawned!");
}

export function spawnDeathMothFromSmallEgg(block) {
  // There's a 10% chance to spawn 1 Death Moth.
  if (Math.random() < 0.1) {
    block.dimension.spawnEntity("hb_hr:death_moth", block.location);
    block.dimension.spawnParticle("hb_hr:death_moth_spawn_dust", block.center());
    block.dimension.spawnParticle("hb_hr:death_moth_spawn", block.center());
    // world.sendMessage("A Death Moth has been spawned from a small egg!");
  }
  block.dimension.runCommand("/fill " + block.location.x + " " + block.location.y + " " + block.location.z + " " + block.location.x + " " + block.location.y + " " + block.location.z + " air destroy");
}

export function triggerEggsFromHiveBlock(spawnBlock, triggerRadius) {
  const volume = new BlockVolume({ x: spawnBlock.location.x - triggerRadius, y: spawnBlock.location.y - triggerRadius, z: spawnBlock.location.z - triggerRadius }, { x: spawnBlock.location.x + triggerRadius, y: spawnBlock.location.y + triggerRadius, z: spawnBlock.location.z + triggerRadius });

  const locations = volume.getBlockLocationIterator();

  for (const location of locations) {
    const block = spawnBlock.dimension.getBlock(location);
    if (!block) continue;
    const blockType = block.typeId;
    if (!blockType.includes("hb_hr:") && !blockType.includes("egg")) continue;

    // world.sendMessage(blockType);
    switch (blockType) {
      case "hb_hr:large_hive_egg":
        spawnDeathMothFromLargeEgg(block, 1, 4);
        break;
      case "hb_hr:small_hive_egg":
        spawnDeathMothFromSmallEgg(block);

        break;
    }
  }
}
export function runIntoSmallDeathMothEggs(block) {
  const center = block.center();
  const blockPos = block.location; // Assuming block.location returns the block's integer coordinates

  // const testBlockVolume = new BlockVolume({ x: blockPos.x, y: blockPos.y, z: blockPos.z }, { x: blockPos.x, y: blockPos.y - 1, z: blockPos.z });

  // Get players within a 1 block radius of the block center
  const players = block.dimension.getEntities({ location: center, maxDistance: 1, type: "minecraft:player", excludeTags: ["hb_hr:testing"] });
  for (const player of players) {
    const pos = player.location;
    // Define player's bounding box assuming a height of 2 blocks.
    const playerBottom = pos.y;
    const playerTop = pos.y + 2; // Player's height is 2 blocks
    const epsilon = 0.01; // Tolerance for vertical checks

    // Check if the player's bounding box intersects with the top surface of the block:
    // - X and Z must be within the block boundaries.
    // - The block's top (blockPos.y + 1) must lie between the player's bottom and top.
    const onBlock = pos.x >= blockPos.x && pos.x < blockPos.x + 1 && pos.z >= blockPos.z && pos.z < blockPos.z + 1 && playerBottom - epsilon <= blockPos.y + 1 && playerTop + epsilon >= blockPos.y + 1;

    // Define an additional horizontal margin for "nearness" – here 0.6 units.
    const margin = 0.4;
    const nearBlock = pos.x >= blockPos.x - margin && pos.x < blockPos.x + 1 + margin && pos.z >= blockPos.z - margin && pos.z < blockPos.z + 1 + margin;

    // Check if the player's bounding box is under the block:
    // - X and Z within the block boundaries.
    // - Player's feet (playerBottom) are below the block's top (blockPos.y + 1)
    const underBlock = pos.x >= blockPos.x && pos.x < blockPos.x + 1 && pos.z >= blockPos.z && pos.z < blockPos.z + 1 && playerBottom < blockPos.y + 1;

    // If the player is on, near, or under the block, trigger the appropriate actions.
    if (onBlock || nearBlock || underBlock) {
      if (block.typeId == "hb_hr:hive_vine") {
        if (!block.permutation.getState("hb_hr:has_eggs") || !block.permutation.getState("hb_hr:full_block")) return;
        const newPermutation = BlockPermutation.resolve("hb_hr:hive_vine", {
          "hb_hr:full_block": true,
          "hb_hr:has_eggs": false,
        });
        block.setPermutation(newPermutation);
        block.dimension.spawnParticle("hb_hr:vine_egg_remove", block.center());
        // block.dimension.spawnParticle("hb_hr:vine_egg_remove", { x: block.location.x + 0.5, y: block.location.y + 0.5, z: block.location.z + 0.5 });
      }
      triggerEggsFromHiveBlock(block, 3);
      // block.dimension.runCommand("/fill " + block.location.x + " " + block.location.y + " " + block.location.z + " " + block.location.x + " " + block.location.y + " " + block.location.z + " air destroy");
      // breakVines(block);
      if (block.typeId == "hb_hr:hive_vine") return;
      spawnDeathMothFromSmallEgg(block);
    }
  }
}
