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:vampire_sword` &&
		item.getComponent("minecraft:cooldown").getCooldownTicksRemaining(player) >
			38 &&
		player.isOnGround
	) {
		//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.vampire_attack @a[r=20] ~~~ 1 1`,
		);
		//Delay commands to match animation
		system.runTimeout(() => {
			//Play sound and particles
			player.runCommandAsync(
				`playsound manalabs_opw.vampire_effect @a[r=20] ~~~ 2 1`,
			);
			player.runCommandAsync(
				`titleraw @p actionbar { \"rawtext\": [ { \"translate\" : \"actionbar.manalabs_opw:vampire_sword\" } ] }`,
			);
			//Commands to run
			player.runCommandAsync(`effect @s slow_falling 5 0 false`);
			player.runCommandAsync(`effect @s invisibility 5 0 false`);
			player.runCommandAsync(`effect @s speed 5 1 false`);
			player.runCommandAsync(`effect @s resistance 5 0 false`);
			player.runCommandAsync(`particle manalabs_opw:vampire_dust ~ ~ ~`);
			player.runCommandAsync(`particle manalabs_opw:vampire_smoke ~ ~ ~`);
			player.runCommandAsync(`particle manalabs_opw:vampire_explode ~ ~ ~`);
			player.applyKnockback(0, 0, 0, 1.5);

			//Get entities within range
			const entities = player.dimension.getEntities({
				location: {
					x: player.location.x,
					y: player.location.y,
					z: player.location.z,
				},
				maxDistance: 8,
			});
			const notTarget = [
				"minecraft:item",
				"minecraft:armor_stand",
				"minecraft:xp_orb",
				"minecraft:arrow",
				"manalabs_opw:mini_snow_golem",
				"manalabs_opw:shadow_vex",
				"manalabs_opw:spell_amethyst",
				"manalabs_opw:spell_bubble",
				"manalabs_opw:spell_cactus",
				"manalabs_opw:spell_ice",
				"manalabs_opw:spell_laser",
				"manalabs_opw:spell_poison",
				"manalabs_opw:spell_shadow",
				"manalabs_opw:spell_skull",
			];
			//Run code for each entity
			entities.forEach((entity) => {
				//Ignore source player and not target array
				if (entity.name == player.name) return;
				if (notTarget.includes(entity.typeId)) return;
				//Commands to run
				entity.runCommandAsync(`damage @s 4 contact`);
				entity.runCommandAsync(`effect @s weakness 5 0`);
				entity.applyKnockback(
					player.location.x - entity.location.x,
					player.location.z - entity.location.z,
					3,
					0,
				);
			});
		}, 8);
	}
});
