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

world.afterEvents.itemUse.subscribe(async (event) => {
	const { itemStack, source } = event;
	
	// Spawn god spear's projectile 
	if (itemStack.typeId === "oct_plev:god_spear") {
		// Setup projectile
		const player = source;
		const viewDirection = player.getViewDirection();
		const HeadLocation = player.getHeadLocation();
		const projectile = player.dimension.spawnEntity("oct_plev:god_spear_projectile", HeadLocation);
		const impulse = { x: viewDirection.x * 2, y: viewDirection.y * 2, z: viewDirection.z * 2 }
		projectile.applyImpulse(impulse);
		
		// Damage the spear
		const item = event.itemStack;
		const durability = item.getComponent(ItemComponentTypes.Durability);
		durability.damage++;
		player.getComponent('equippable').setEquipment('Mainhand', item);


		// Remove item when it should be broken
		const maxDurability = item.getComponent("durability").maxDurability;
		const actualDamage = item.getComponent("durability").damage;
		if(actualDamage >= maxDurability) {
			player.runCommand('/replaceitem entity @s slot.weapon.mainhand 0 air');
			player.runCommand('/playsound random.break @s ~ ~ ~');
		}
	}
});


const TAG_KNOCKBACK_IMMUNITY = 'oct_plev_god_spear_knockback_immunity'

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:god_spear") {
        player.addTag(TAG_KNOCKBACK_IMMUNITY);
        if (enemy.isValid()) {
			enemy.runCommand('/summon oct_plev:god_spear_knockback ^ ^ ^0.1 ~ ~');
		}		
        let tagRemovingDelay = system.runTimeout(() => {
            player.removeTag(TAG_KNOCKBACK_IMMUNITY);
            system.clearRun(tagRemovingDelay);
        }, 1000);
    }
});