import { ItemStack, EntityDieAfterEvent } from "@minecraft/server";
import { getScoreUtility, setScoreUtility, operationScoreUtility } from "./scoreboard";
import { skillAllName } from "./skill_list";
import { getEntityDataById } from "./entity";
import { updateStatus } from "./status";


/**
 * @param {EntityDieAfterEvent} ev 
 * @returns 
 */
export function entityDie(ev){
	const deadEntity = ev.deadEntity;
	const damagingEntity = ev.damageSource.damagingEntity;
	const damageCause = ev.damageSource.cause;
	if(damageCause == "selfDestruct") return;
	if (deadEntity.typeId == "minecraft:player"){
		deadEntity.playAnimation("animation.addon_mob.die",{nextState:"third_person",blendOutTime:0.25,controller:"controller.animation.player.root",stopExpression:"q.any_animation_finished"});
		deadEntity.triggerEvent("no_nen");
	}
	if(damagingEntity != undefined){
		if (damagingEntity.typeId == "minecraft:player"){
			const entityDieName = deadEntity.typeId.split("hxc:")[1];
			rewardExp(damagingEntity,deadEntity);
			damagingEntity.runCommand(`function advancement/kill/${entityDieName}`);
		}
		else if(damageCause == "entityExplosion"){
			const player = deadEntity?.dimension.getPlayers({maxDistance:64,location:deadEntity.location})[0];
			if (player) rewardExp(player,deadEntity);
		}
	}
	else{
		if(damageCause == "contact") return;
		const player = deadEntity.dimension.getPlayers({maxDistance:64,location:deadEntity.location})[0];
		if (player) rewardExp(player,deadEntity);
	}
};
/**
 * @param {Player} player 
 * @param {Entity} deadEntity 
 */
function rewardExp(player,deadEntity){
	const deadEntityId = deadEntity.typeId;
	const currentExp = player.getProperty("hxc:exp");
	const Level = player.getProperty("hxc:level");
	const MAX_EXP = ((Level * 5) + 20) + (Level * 10);
	const entityData = getEntityDataById(deadEntityId);
	const rewardExp = entityData.rewardExp;
	const addExp = currentExp + rewardExp;
	if (Level <= 200){
		player.sendMessage({rawtext:[{text:`§b`},{translate:"form.status.body.1"},{text:`§f+${rewardExp}`}]});
		player.playSound("random.orb",{volume:0.75});
		player.setProperty("hxc:exp",addExp);
	}
	if(currentExp >= MAX_EXP && Level >= 200){
		player.setProperty("hxc:exp",MAX_EXP);
	}
	updateStatus(player);
}