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",
		"manalabs_opw:mini_snow_golem",
	];
	//Check item and cooldown
	if (
		item.typeId === `manalabs_opw:ice_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(`particle manalabs_opw:ice_streaks ~ ~-4 ~`);
		player.runCommandAsync(
			`playsound manalabs_opw.icesword_effect @a[r=20] ~~~ 1 1.2`,
		);
		//Delay commands to match animation
		system.runTimeout(() => {
			//Play sound and particles
			player.runCommandAsync(`playsound use.snow @a[r=20] ~~~ 1 1.2`);
			player.runCommandAsync(
				`particle minecraft:critical_hit_emitter ~ ~0.5 ~`,
			);
			player.runCommandAsync(`particle manalabs_opw:ice_frostfire ~ ~0.5 ~`);
			player.runCommandAsync(
				`titleraw @p actionbar { \"rawtext\": [ { \"translate\" : \"actionbar.manalabs_opw:ice_sword\" } ] }`,
			);
			player.runCommandAsync(`summon manalabs_opw:spell_ice ~4~~`);
			player.runCommandAsync(`summon manalabs_opw:spell_ice ~~~4`);
			player.runCommandAsync(`summon manalabs_opw:spell_ice ~-4~~`);
			player.runCommandAsync(`summon manalabs_opw:spell_ice ~~~-4`);
			//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(`summon manalabs_opw:spell_ice ~~~`);
				entity.runCommandAsync(`effect @s slowness 5 10 false`);
				entity.runCommandAsync(`particle manalabs_opw:ice_frostfire ~ ~0.5 ~`);
				system.runTimeout(() => {
					entity.runCommandAsync(`damage @s 5 contact`);
				}, 5);
			});
		}, 8);
	}
});
