import { world, ItemStack, GameMode } from "@minecraft/server";

// This array defines the weapon items that will lose durability.
const weaponTypeIds = [
	"manalabs_opw:celestial_sword",
	"manalabs_opw:cosmic_rings",
	"manalabs_opw:cosmic_sword",
	"manalabs_opw:hand_sword",
	"manalabs_opw:ice_sword",
	"manalabs_opw:kyro_sword",
	"manalabs_opw:laser_sword",
	"manalabs_opw:mystic_axe",
	"manalabs_opw:poison_sword",
	"manalabs_opw:shadow_sword",
	"manalabs_opw:skull_crusher",
	"manalabs_opw:skull_sword",
	"manalabs_opw:titan_sword",
	"manalabs_opw:vampire_sword",
];

world.afterEvents.itemUse.subscribe((data) => {
	const item = data.itemStack;
	const player = data.source;

	// This returns if item is undefined or if the player is in Creative.
	if (!item || player.matches({ gameMode: GameMode.creative })) return;
	// If item has cooldown remaining, don't change durability

	// Checks to see if has Weapon from array
	if (weaponTypeIds.includes(item.typeId)) {
		if (
			item
				.getComponent("minecraft:cooldown")
				.getCooldownTicksRemaining(player) < 38 &&
			item
				.getComponent("minecraft:cooldown")
				.getCooldownTicksRemaining(player) > 0
		)
			return;

		// This retrieves the player's equippable component.
		const playerEquippableComp = player.getComponent("equippable");

		// This returns if playerEquippableComp is undefined.
		if (!playerEquippableComp) return;

		// This retrieves the enchantable component of the item.
		const itemEnchantmentComp = item.getComponent("minecraft:enchantable");
		const unbreakingLevel =
			itemEnchantmentComp?.getEnchantment("unbreaking")?.level ?? 0;

		// Calculates the chance of an item breaking based on its unbreaking level. This is the vanilla unbreaking formula.
		const breakChance = 100 / (unbreakingLevel + 1);
		// Generates a random chance value between 0 and 100.
		const randomizeChance = Math.random() * 100;

		// This returns if breakChance is less than randomizeChance.
		if (breakChance < randomizeChance) return;

		// This retrieves the durability component of the item.
		const itemDurabilityComp = item.getComponent("durability");

		// This returns if itemDurabilityComp is undefined.
		if (!itemDurabilityComp) return;

		// This will set the new durability value.
		itemDurabilityComp.damage += 1;

		// Declares and checks if the item is out of durability
		const maxDurability = itemDurabilityComp.maxDurability;
		const currentDamage = itemDurabilityComp.damage;
		if (currentDamage >= maxDurability) {
			// If the item is out of durability, plays the item breaking sound and removes the item
			player.playSound("random.break", {
				pitch: 1,
				location: player.location,
				volume: 1,
			});
			playerEquippableComp.setEquipment(
				"Mainhand",
				new ItemStack("minecraft:air", 1),
			);
		} else if (currentDamage < maxDurability) {
			// This sets the item in the player's selected slot.
			playerEquippableComp.setEquipment("Mainhand", item);
		}
	}
});
