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

export function checkInventoryHaveItem(player, itemId, amount) {
  const inventory = player.getComponent("minecraft:inventory")
  const container = inventory.container
  let foundAmount = 0
  for (let i = 0; i < container.size; i++) {
    const currentSlotItem = container.getItem(i)
    if (currentSlotItem?.typeId == itemId) {
      foundAmount += currentSlotItem.amount
      if (foundAmount >= amount) return true
    }
  }
  
  const equippable = player.getComponent("minecraft:equippable")
  const offhand = equippable.getEquipment("Offhand")
  if(offhand?.typeId == itemId && offhand.amount >= amount) return true
  return foundAmount >= amount
}

export function applyKnockback(player, victim, strength) {
  // Get the positions of the player and victim
  let playerPosition = player.location;  // assuming this is a Vector3
  let victimPosition = victim.location;  // assuming this is a Vector3
  // Calculate the direction from the victim to the player (this is the vector from victim to player)
  let dx = playerPosition.x - victimPosition.x;
  let dy = playerPosition.y - victimPosition.y;
  let dz = playerPosition.z - victimPosition.z;

  // Normalize this vector (so the direction is consistent regardless of distance)
  let magnitude = Math.sqrt(dx * dx + dy * dy + dz * dz);
  dx /= magnitude;
  dy /= magnitude;
  dz /= magnitude;

  // Now calculate the knockback direction by inverting the vector (moving away from the player)
  dx = -dx;
  dy = -dy;
  dz = -dz;
  
  if(dx == NaN || dy == NaN || dz == NaN) 
    return;

  // Apply the knockback impulse (scaled by strength)
  victim.clearVelocity();
  victim.applyImpulse({
    x: dx * strength,
    y: dy * strength,
    z: dz * strength
  });
}
export function sleep(ticks) {
  return new Promise(resolve => {
    system.runTimeout(() => resolve(ticks), ticks);
  });
}

export function getRandomFloat(min, max) {
  return Math.random() * (max - min) + min;
}

export function fromPercent(value) {
  return value / 100;
}

export function fromSecond(seconds) {
  return seconds * 20; // Convert to ticks
}

export function clamp(value, min, max) {
  return Math.min(Math.max(value, min), max);
}

export function getRandomNumber(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}