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

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:kyro_sword` &&
		item.getComponent("minecraft:cooldown").getCooldownTicksRemaining(player) >
			38
	) {
		//Play animations
		player.playAnimation(`animation.manalabs_opw.first_person_sword_attack`, {
			nextState: `none`,
			blendOutTime: 1,
			stopExpression: `query.any_animation_finished`,
			controller: `controller_name1`,
		});
		player.playAnimation(`animation.manalabs_opw.third_person_sword_attack`, {
			nextState: `none`,
			blendOutTime: 1,
			stopExpression: `query.any_animation_finished`,
			controller: `controller_name2`,
		});
		player.runCommandAsync(
			`playsound manalabs_opw.kyro_effect @a[r=20] ~~~ 1 1.2`,
		);
		//Delay commands to match animation
		system.runTimeout(() => {
			//Play sound and particles
			player.runCommandAsync(`particle manalabs_opw:kyro_cactus ~ ~0.5 ~`);
			player.runCommandAsync(
				`particle minecraft:ice_evaporation_emitter ~ ~0.5 ~`,
			);
			player.runCommandAsync(
				`titleraw @p actionbar { \"rawtext\": [ { \"translate\" : \"actionbar.manalabs_opw:kyro_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 6 contact`);
				entity.runCommandAsync(`summon manalabs_opw:spell_cactus ~~~`);
				entity.runCommandAsync(
					`playsound manalabs_opw.kyro_attack @a[r=8] ~~~ 2 1`,
				);
				entity.runCommandAsync(`particle manalabs_opw:kyro_cactus ~ ~1 ~`);
			});
		}, 8);
	}
});
