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

const TAG_AREA_ATTACK = "oct_plev_flail_area_attack"

// Area attack and chance to stun entity
world.afterEvents.itemStartUse.subscribe( async (event) => {
	const { itemStack, source } = event;
	const player = source;
	const item = itemStack.typeId;

	
	if (item == "oct_plev:flail") {
		let usingFlail = system.runInterval(() => {
			player.addTag(TAG_AREA_ATTACK);
			player.runCommand("/damage @e[type=!minecraft:item,tag=!oct_plev_flail_area_attack,r=3] 6 entity_attack entity @s");
			player.runCommand("/execute as @e[type=!minecraft:item,tag=!oct_plev_flail_area_attack,r=3] run function oct/plev/flail/flail_stun");
			player.removeTag(TAG_AREA_ATTACK);
		}, 10)

		world.afterEvents.itemStopUse.subscribe( async () => {
			system.clearRun(usingFlail)
		});
	}
});

// Melee attack, chance to stun enemy
world.afterEvents.entityHitEntity.subscribe(data => {
    const player = data.damagingEntity
	const enemy = data.hitEntity
    
    if (player.typeId === 'minecraft:player' && player.getComponent("equippable").getEquipment("Mainhand")?.typeId === "oct_plev:flail") {
        enemy.runCommand("/function oct/plev/flail/flail_stun");
	}
})