import { world } from '@minecraft/server';

const MAX_PACK_COUNT = 64;

world.afterEvents.dataDrivenEntityTrigger.subscribe(event => {
    const { entity } = event
    const { dimension, location, typeId } = entity
    const randomCount = Math.floor(Math.random() * 2) + 1

    let packNumber = world.getDynamicProperty(typeId + '_number') ?? -1
    packNumber++

    if (packNumber == MAX_PACK_COUNT) packNumber = 0
    world.setDynamicProperty(typeId + '_number', packNumber)

    packNumber = packNumber.toString()

    for (let i = 0; i < randomCount; i++) {
        const memberLocation = findSafeSpawnLocation(dimension, location, 3)
        const member = dimension.spawnEntity(typeId, memberLocation)
        member.addTag(packNumber)
    }

    entity.addTag(packNumber)

}, { eventTypes: ['cyd_dino:as_pack'] })

function findSafeSpawnLocation(dimension, center, radius) {
    for (let i = 0; i < 10; i++) {
        const randomOffset = {
            x: center.x + (Math.random() * radius * 2 - radius),
            y: center.y,
            z: center.z + (Math.random() * radius * 2 - radius)
        }

        const block = dimension.getBlock(randomOffset)
        if (block && block.isAir) return randomOffset
    }

    return center
}