import { Entity, Player, world } from '@minecraft/server';

/**
 * @param {Entity} entity
 * @param {Player} player
 * @param {number} amount  
 */
export function updateTrust(entity = Entity, player, amount) {
    if (!entity || !player) return;

    try {
        const isBaby = entity.typeId.includes('baby_')
        const newAmount = Math.max((entity.getDynamicProperty(`trust:${player.id}`) ?? 0) + amount, 0)
        if (newAmount >= 100) {
            entity.clearDynamicProperties()
            entity.getComponent('tameable')?.tame(player)
            if (!isBaby) player.setPropertyOverrideForEntity(entity, 'cyd_dino:taming_percentage', 100)
        } else {
            entity.setDynamicProperty(`trust:${player.id}`, newAmount)
            if (!isBaby) player.setPropertyOverrideForEntity(entity, 'cyd_dino:taming_percentage', newAmount)
        }
    } catch ($) { }
}

world.afterEvents.dataDrivenEntityTrigger.subscribe(({ entity }) => {
    updateTrust(entity, entity.dimension.getEntities({ closest: 1, location: entity.location, type: 'minecraft:player', maxDistance: 16 })[0], 100)
}, { eventTypes: ['cyd_dino:hatch'] })