import { EntityInventoryComponent } from "@minecraft/server";
import { itemLore } from "./lore.js";

/**
 * @param {import("@minecraft/server").Player} player
 */
export async function inventory(player) {
  const inventory = player.getComponent(EntityInventoryComponent.componentId);
  if (!(inventory instanceof EntityInventoryComponent) || !inventory.container) {
    return;
  }

  /** @type {Record<string, {type: "scoreboard" | "property", hasItem: boolean, effect?: string}>} */
  const toggleArtifacts = {
    "myth:ring_of_swiftness": {
      type: "scoreboard",
      hasItem: false,
      effect: "speed",
    },
    "myth:slimy_boots": {
      type: "scoreboard",
      hasItem: false,
      effect: "jump_boost",
    },
    "myth:shield_of_ashes": {
      type: "scoreboard",
      hasItem: false,
      effect: "resistance",
    },
    "myth:eye_of_sight": {
      type: "scoreboard",
      hasItem: false,
      effect: "night_vision",
    },
    "myth:amulet_of_attraction": {
      type: "scoreboard",
      hasItem: false,
    },
    "myth:silver_shovel": {
      type: "scoreboard",
      hasItem: false,
      effect: "haste",
    },
    "myth:skull": {
      type: "scoreboard",
      hasItem: false,
    },
    "myth:forest_amulet": {
      type: "property",
      hasItem: false,
    },
    "myth:leam_hammer": {
      type: "property",
      hasItem: false,
    },
    "myth:shield_of_shadow": {
      type: "property",
      hasItem: false,
    },
    "myth:torch": {
      type: "property",
      hasItem: false,
    },
  };

  for (let i = 0; i < inventory.container.size; i++) {
    const item = inventory.container.getItem(i);
    if (!item) {
      continue;
    }
    if (item.typeId in toggleArtifacts) {
      toggleArtifacts[item.typeId].hasItem = true;
    }
    await itemLore(player, item, i);
  }

  for (const id in toggleArtifacts) {
    const { type, hasItem, effect } = toggleArtifacts[id];
    if (hasItem) {
      continue;
    }
    if (type === "scoreboard") {
      const objective = id.split(":")[1];
      if (effect && player.matches({ scoreOptions: [{ objective, minScore: 1 }] })) {
        player.removeEffect(effect);
      }
      player.runCommandAsync(`scoreboard players reset @s ${objective}`);
    } else if (player.getProperty(id)) {
      player.setProperty(id, false);
    }
  }
}
