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


const monsterNo10Id = "pm_m8:monster_no_10";
const start = "start";

//blood counter
const monster10id = "pm_m8:monster_no_10";
const bloodCounterNameSpace = "pm_m8_monster_no_10_blood_counter";
const scriptEventOption = {namespaces : [bloodCounterNameSpace]};
/**
 * @type {import("@minecraft/server").EntityEventOptions}
 */
const hurtEventOption = {entityTypes: [monster10id]}
let bloodCounterEntities = new Map();


/**
 * @param {EntityHurtAfterEvent} event 
 */
function bloodCounterCallback(event){
    const hurtEntity = event.hurtEntity;
    const sourceEntity = event.damageSource.damagingEntity;
    if (!bloodCounterEntities.has(hurtEntity.id)) return;
    if (sourceEntity !== null && sourceEntity !== undefined) {
        sourceEntity.applyDamage(event.damage);
        bloodCounterEntities.set(hurtEntity.id, bloodCounterEntities.get(hurtEntity.id) + event.damage);
    }
}


/**
 * @param {Entity} entity 
 */
function bloodCounterStart(entity) {
    bloodCounterEntities.set(entity.id, 0);
}


/**
 * @param {Entity} entity 
 */
function bloodCounterEnd(entity) {
    // console.warn("damage" + Math.floor(bloodCounterEntities.get(entity.id)));
    entity.runCommand(`/damage @e[type=!pm_m8:monster_no_10,r=8] ${Math.floor(bloodCounterEntities.get(entity.id))} entity_attack entity @s`)
    bloodCounterEntities.delete(entity.id);
}


/**
 * @param {ScriptEventCommandMessageAfterEvent} event 
 */
function bloodCounterController(event){
    const sourceEntity = event.sourceEntity;
    if (!sourceEntity) return;
    if (event.message == start) {
        bloodCounterStart(sourceEntity);
    }
    else {
        bloodCounterEnd(sourceEntity);
    }
}

world.afterEvents.entityHurt.subscribe(bloodCounterCallback, hurtEventOption);
system.afterEvents.scriptEventReceive.subscribe(bloodCounterController, scriptEventOption);