// @ts-check
import { world, Player, system } from "@minecraft/server";

/**
 * @param {Player} player
 * @param {number} slot
 */
function setSlotToAir(player, slot) {
  if (slot < 9) {
    player.runCommandAsync(`replaceitem entity @s slot.hotbar ${slot} air`);
  } else player.runCommandAsync(`replaceitem entity @s slot.inventory ${slot - 9} air`);
}

/**
 * @param {Player} player
 * @param {string[]} itemIds
 */
function itemQuery(player, itemIds) {
  /** @type {any} */
  const comp = player.getComponent("inventory");
  const inv = comp.container;
  let amount = 0;
  let info = [];
  for (let i = 0; i < inv.size; i++) {
    const item = inv.getItem(i);
    if (!item) continue;

    const { typeId, amount: iAmount, data } = item;
    if (itemIds.includes(typeId.replace("minecraft:", ""))) {
      amount += iAmount;
      info.push({
        slot: i,
        item: { typeId, amount: iAmount, data },
      });
    }
  }
  return {
    amount,
    slots: info,
  };
}


function healthPowerup(player) {
  /** @type {any} */
  const hp = player.getComponent("health");
  if (hp.current <= 0) return;
  const itemInfo = itemQuery(player, ["js:health"]);
  if (itemInfo.amount <= 0) return;
  for (let slot of itemInfo.slots) setSlotToAir(player, slot.slot);

  hp.setCurrent(hp.current + itemInfo.amount);
  player.playSound("misc.hp_pickup");
}


function handleAmmo(player, item, objective) {
  const itemInfo = itemQuery(player, [item]);
  if (itemInfo.amount <= 0) {
	player.runCommandAsync(`tag @s remove ${objective}`);
	return
  };
  for (let slot of itemInfo.slots);
	player.runCommandAsync(`tag @s add ${objective}`);
};

const ammoItems = {
  "js:oblivion_ammo": "has oblivion_ammo",
  "js:svd_ammo": "has_havoc_ammo",
  "js:fp6_ammo": "has_fp6_ammo",
  "js:sh_plasma_cannon_ammo": "has_sh_plasma_cannon_ammo",
  "js:hk417_ammo": "has_hk417_ammo",
  "js:flamethrower_ammo": "has_flamethrower_ammo",
  "minecraft:diamond": "has_diamond",
  "minecraft:lapis_block": "has_lapis_block",
  "minecraft:netherite_ingot": "has_netherite_ingot",
  "minecraft:diamond_block": "has_diamond_block"
}

system.run(function playerTick(ev) {
  system.run(playerTick);

  for (let plr of world.getPlayers()) {
    healthPowerup(plr);
    for (let itemId in ammoItems) {
	  handleAmmo(plr, itemId, ammoItems[itemId]);
    }
  }
});



