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

const TAG_AREA_ATTACK = "oct_plev_warhammer_knockback_immunity"

const TAG_WARHAMMER_COOLDOWN = "oct_plev_warhammer_cooldown"
const TAG_WARHAMMER_COOLDOWN_2 = "oct_plev_warhammer_cooldown_2"

// Area attack and stun
world.afterEvents.itemStartUse.subscribe( async (event) => {
	const { itemStack, source } = event;
	const player = source;
	const item = itemStack.typeId;
	
	if (item == "oct_plev:warhammer") {
			player.addTag(TAG_AREA_ATTACK);
			player.runCommand("/execute rotated ~ 0 positioned ^ ^ ^2 run summon oct_plev:warhammer_knockback ~ ~-0.5 ~");

			let tagRemovingDelay = system.runTimeout(() => {
				player.removeTag(TAG_AREA_ATTACK);
				system.clearRun(tagRemovingDelay);
			}, 1000);
	}
});


function main() {
	for (let player of world.getAllPlayers()) {
		// Cursed Cannon cooldown
		if (player.hasTag(TAG_WARHAMMER_COOLDOWN) && !player.hasTag(TAG_WARHAMMER_COOLDOWN_2)) {
			player.addTag(TAG_WARHAMMER_COOLDOWN_2);
			let WarhammerCooldown = system.runTimeout(() => {
				player.removeTag(TAG_WARHAMMER_COOLDOWN);
				player.removeTag(TAG_WARHAMMER_COOLDOWN_2);
				system.clearRun(WarhammerCooldown);
			}, 30);
		}
	}
}
system.runInterval(main, 5);

world.afterEvents.playerSpawn.subscribe((event) => {
	// Remove cooldown tag on join
	event.player.removeTag(TAG_WARHAMMER_COOLDOWN_2);
});