import {world,BlockVolume,BlockPermutation} from '@minecraft/server';
import {spawnerLoc,findBlocks} from '../utils.js';

world.afterEvents.entitySpawn.subscribe(event => {
	const {entity} = event;
	try {
		if (!entity || entity.getComponent('item') || entity.getComponent('projectile') || (entity.getComponent('minecraft:type_family') && entity.getComponent('minecraft:type_family').hasTypeFamily('inanimate'))) return;
		const location = entity.location;
		const dimension = entity.dimension;
		const nearbySpawner = findBlocks('minecraft:mob_spawner', dimension, location, 4);
    
		if (nearbySpawner) {
			const key = `${nearbySpawner.location.x},${nearbySpawner.location.y},${nearbySpawner.location.z}`;
			if (!spawnerLoc.has(key)) spawnerLoc.set(key, 0);
			const count = spawnerLoc.get(key) + 1;
			spawnerLoc.set(key, count);
			console.log(`mob spawned: ${count}`);
			if (count === 16) {
				nearbySpawner.setPermutation(BlockPermutation.resolve('minecraft:air'));
				spawnerLoc.delete(key);
			}
		}
	} catch (e) {}
});
