import { world, system } from "@minecraft/server";
const SJhorizontal = 5;
const SJvertical = 0.5;

world.afterEvents.itemUse.subscribe((data) => {
	const item = data.itemStack;
	const player = data.source;
	//Get player name to filter out when ability triggers
	const playerName = player.name;
	//Array of entities to ignore
	const notTarget = [
		"minecraft:item",
		"minecraft:armor_stand",
		"minecraft:xp_orb",
	];
	//Check item and cooldown
	if (
		item.typeId === `manalabs_opw:hand_sword` &&
		item.getComponent("minecraft:cooldown").getCooldownTicksRemaining(player) >
			38
	) {
		//Play animations
		player.playAnimation(
			`animation.manalabs_opw.first_person_hand_sword_attack`,
			{
				nextState: `none`,
				blendOutTime: 1,
				stopExpression: `query.any_animation_finished`,
				controller: `controller_name1`,
			},
		);
		player.playAnimation(
			`animation.manalabs_opw.third_person_hand_sword_attack`,
			{
				nextState: `none`,
				blendOutTime: 1,
				stopExpression: `query.any_animation_finished`,
				controller: `controller_name2`,
			},
		);
		player.runCommandAsync(`particle manalabs_opw:hand_infernal_cyclone ~~~`);
		player.runCommandAsync(`particle manalabs_opw:hand_infernal_cyclone_2 ~~~`);
		player.runCommandAsync(
			`playsound manalabs_opw.handsword_effect @a[r=20] ~~~ 1 1.2`,
		);
		//Delay commands to match animation
		system.runTimeout(() => {
			//Lunge player
			const dir = player.getViewDirection();
			player.applyKnockback(dir.x, dir.z, SJhorizontal, SJvertical);
			//Play sound and particles
			player.runCommandAsync(
				`playsound manalabs_opw.handsword_attack @a[r=20] ~~~ 1 1`,
			);
			player.runCommandAsync(`particle manalabs_opw:fire_tornado ~~~`);
			player.runCommandAsync(
				`particle manalabs_opw:hand_infernal_cyclone_2 ~~~`,
			);
			player.runCommandAsync(
				`titleraw @p actionbar { \"rawtext\": [ { \"translate\" : \"actionbar.manalabs_opw:hand_sword\" } ] }`,
			);
			//Get entities within range
			const entities = player.dimension.getEntities({
				location: {
					x: player.location.x,
					y: player.location.y,
					z: player.location.z,
				},
				maxDistance: 8,
			});
			//Run code for each entity
			entities.forEach((entity) => {
				//Ignore source player and not target array
				if (entity.name == playerName) return;
				if (notTarget.includes(entity.typeId)) return;
				//Commands to run
				entity.runCommandAsync(`damage @s 5 contact`);
				entity.runCommandAsync(
					`particle manalabs_opw:hand_infernal_cyclone ~~~`,
				);
				entity.runCommandAsync(
					`particle manalabs_opw:hand_infernal_cyclone ~~0.4~`,
				);
				entity.setOnFire(10, true);
			});
		}, 10);
	}
});
