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

world.afterEvents.itemUse.subscribe(async (event) => {
	const { itemStack, source } = event;
	const player = source;
	
	// Spawn god spear's projectile 
	if (itemStack.typeId === "oct_plev:harpoon_gun" && player.runCommand("/testfor @s[hasitem={item=oct_plev:harpoon}]").successCount) {
		// Remove ammo
		player.runCommand('/clear @s[m=!creative] oct_plev:harpoon 0 1');
		player.runCommand('/playsound crossbow.shoot @a ~ ~ ~ 1 1.7');

		// Setup projectile
		const viewDirection = player.getViewDirection();
		const HeadLocation = player.getHeadLocation();
		const projectile = player.dimension.spawnEntity("oct_plev:harpoon_gun_projectile", HeadLocation);
		const impulse = { x: viewDirection.x * 2, y: viewDirection.y * 2, z: viewDirection.z * 2 }
		projectile.applyImpulse(impulse);
		
		// Damage the harpoon gun
		const item = event.itemStack;
		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 ~ ~ ~');
		}
	}
});