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:poison_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.poison_attack @a[r=20] ~~~ 1 1`,
		);
		//Delay commands to match animation
		system.runTimeout(() => {
			//Play sound and particles
			player.runCommandAsync(
				`playsound manalabs_opw.poison_effect @a[r=20] ~~~ 1 1`,
			);
			player.runCommandAsync(
				`titleraw @p actionbar { \"rawtext\": [ { \"translate\" : \"actionbar.manalabs_opw:poison_sword\" } ] }`,
			);
			player.dimension.spawnParticle(`minecraft:egg_destroy_emitter`, {
				x: player.location.x + player.getViewDirection().x * 2,
				y: player.location.y,
				z: player.location.z + player.getViewDirection().z * 2,
			});
			player.dimension.spawnParticle(`manalabs_opw:poison_toxic_area`, {
				x: player.location.x + player.getViewDirection().x * 2,
				y: player.location.y,
				z: player.location.z + player.getViewDirection().z * 2,
			});
			const spell = player.dimension.spawnEntity(`manalabs_opw:spell_poison`, {
				x: player.location.x + player.getViewDirection().x * 2,
				y: player.location.y,
				z: player.location.z + player.getViewDirection().z * 2,
			});
			const interval = system.runInterval(() => {
				if (spell.isValid() == true) {
					spell.runCommandAsync(
						`effect @e[type=!item,family=!dummy,name=!"${player.name}",r=5] fatal_poison 10 0 false`,
					);
				} else {
					system.clearRun(interval);
				}
			}, 1);
		}, 8);
	}
});
