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

world.afterEvents.itemUse.subscribe(async (event) => {
	const { itemStack, source } = event;
	const player = source;

	// Right click interaction
	if (itemStack.typeId === "oct_plev:grappling_hook") {

		// Despawn previous grappling hook entities
		player.runCommand("/tag @s add oct_plev_hook_shoot");
		player.runCommand("/execute as @e[type=oct_plev:grappling_hook_projectile] if score @s oct_plev_hook_owner = @a[c=1,tag=oct_plev_hook_shoot] oct_plev_hook_owner run event entity @s despawn");
		player.runCommand("/tag @s remove oct_plev_hook_shoot");

		// Shoot Projectile
		const viewDirection = player.getViewDirection();
		const HeadLocation = player.getHeadLocation();	
		const projectile = player.dimension.spawnEntity("oct_plev:grappling_hook_projectile", HeadLocation);	
		const impulse = {	
			x: viewDirection.x * 5,
			y: viewDirection.y * 5,
			z: viewDirection.z * 5
		};		
		projectile.applyImpulse(impulse);

		// Sound effect
		player.runCommand('/playsound oct_plev.sound.grappling_hook_extended @a ~ ~ ~');
	}
});