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

world.afterEvents.itemUse.subscribe((data) => {
	const item = data.itemStack;
	const player = data.source;
	//Check item and cooldown
	if (
		item.typeId === `manalabs_opw:laser_sword` &&
		item.getComponent("minecraft:cooldown").getCooldownTicksRemaining(player) >
			8
	) {
		//Play animations
		player.playAnimation(
			`animation.manalabs_opw.first_person_laser_sword_attack`,
			{
				nextState: `none`,
				blendOutTime: 1,
				stopExpression: `query.any_animation_finished`,
				controller: `controller_name1`,
			},
		);
		player.playAnimation(
			`animation.manalabs_opw.third_person_laser_sword_attack`,
			{
				nextState: `none`,
				blendOutTime: 1,
				stopExpression: `query.any_animation_finished`,
				controller: `controller_name2`,
			},
		);
		//Delay commands to match animation

		player.runCommandAsync(
			`playsound manalabs_opw.laser_attack @a[r=20] ~~~ 1 1`,
		);
		system.runTimeout(() => {
			player.runCommandAsync(
				`playsound manalabs_opw.laser_effect @a[r=20] ~~~ 1 4`,
			);
			player.runCommandAsync(
				`titleraw @p actionbar { \"rawtext\": [ { \"translate\" : \"actionbar.manalabs_opw:laser_sword\" } ] }`,
			);
			shoot_laser(player);
		}, 5);
	}

	function shoot_laser(player) {
		const viewDirection = player.getViewDirection();
		const HeadLocation = player.getHeadLocation();
		const projectile = player.dimension.spawnEntity(
			"manalabs_opw:spell_laser",
			HeadLocation,
		);
		const impulse = {
			x: viewDirection.x * 4,
			y: viewDirection.y * 6,
			z: viewDirection.z * 4,
		};
		projectile.setRotation(viewDirection);
		projectile.applyImpulse(impulse);
	}
});
