import { world } from "@minecraft/server";

/* 
Checks which item is used in the mainhand
Runs cooldown function if a specific item is in the mainhand:
- Checks if the player has a tag; otherwise, tags them and sets the cooldown scoreboard to the tick amount of time the cooldown should stay
*/

export function itemUseController(event) {
  const typeId = event.source.typeId;
  if (typeId !== "minecraft:player") {
    return;
  }
  const holdingItem = event.source.getComponent("equippable").getEquipment("Mainhand");

  if (holdingItem == undefined) {
    return;
  } else {
    if (holdingItem.typeId == "ent_co:throwable_tnt") {
      let playerViewDirection = event.source.getViewDirection();
      const head = event.source.getHeadLocation();
      let projectile = world.getDimension(event.source.dimension.id).spawnEntity("ent_co:tnt_throwable_projectile", offsetPositionInDirection(head, playerViewDirection, 3));
      projectile.clearVelocity();
      projectile.applyImpulse({ x: playerViewDirection.x * 2, y: playerViewDirection.y * 2, z: playerViewDirection.z * 2 });
      event.source.runCommand("/clear @s ent_co:throwable_tnt 0 1");
    }
  }
}

function offsetPositionInDirection(position, viewDirection, offset) {
  // Ensure the view direction vector is normalized
  const normalizedViewDirection = normalizeVector3(viewDirection);

  // Calculate the offset in each axis based on the normalized view direction
  const offsetX = normalizedViewDirection.x * offset;
  const offsetY = normalizedViewDirection.y * offset;
  const offsetZ = normalizedViewDirection.z * offset;

  // Create a new Vector3 representing the offset position
  // const offsetPosition = new Vector3(position.x + offsetX, position.y + offsetY, position.z + offsetZ);

  const offsetPosition = {
    x: position.x + offsetX,
    y: position.y + offsetY,
    z: position.z + offsetZ,
  };

  return offsetPosition;
}

function normalizeVector3(vector) {
  const length = Math.sqrt(vector.x * vector.x + vector.y * vector.y + vector.z * vector.z);
  if (length !== 0) {
    return {
      x: vector.x / length,
      y: vector.y / length,
      z: vector.z / length,
    };
  } else {
    return {
      x: 0,
      y: 0,
      z: 0,
    };
    // Avoid division by zero
  }
}
