import { system, world, ItemComponentTypes } from "@minecraft/server";

world.beforeEvents.playerBreakBlock.subscribe(data => {
	const player = data.player;
	const item = data.itemStack;

	if (player.typeId === 'minecraft:player' && player.getComponent("equippable").getEquipment("Mainhand")?.typeId === "oct_plev:special_pickaxe") {
		system.run(() => {
			// Destory blocks
			player.runCommand("/execute as @s run function oct/plev/special_pickaxe/ray_init");

			// Damage the tool
			const durability = item.getComponent(ItemComponentTypes.Durability);
			durability.damage++;
			player.getComponent('equippable').setEquipment('Mainhand', item);

			// Remove item when it should be broken
			const maxDurability = item.getComponent("durability").maxDurability;
			const actualDamage = item.getComponent("durability").damage;
			if(actualDamage === maxDurability) {
				player.runCommand('/replaceitem entity @s slot.weapon.mainhand 0 air');
				player.runCommand('/playsound random.break @s ~ ~ ~');
			}
		});
    }
});