import {world,BlockPermutation,ItemStack} from "@minecraft/server";
import {pickUpItems,grassTypes,cropTypes} from '../config.js';
import {spawnerLoc,findBlocks} from '../utils.js';

world.afterEvents.playerBreakBlock.subscribe(event => {
	const {block,brokenBlockPermutation,dimension,player,itemStack} = event;
	if (!block) return;
	const rng = Math.floor(Math.random()*100);
	const crop = cropTypes[brokenBlockPermutation.type.id];
	const {x,y,z} = block.location;
	const blocks = pickUpItems[block.above().typeId];
	if (blocks) {
		dimension.spawnItem(new ItemStack(blocks.item), block.above().location);
		block.above().setPermutation(BlockPermutation.resolve('minecraft:air'))
	}
	if (brokenBlockPermutation.type.id == 'minecraft:mob_spawner') {
		const key = `${x},${y},${z}`;
		const loot = 'blocks/spawner';
		if (spawnerLoc.has(key)) spawnerLoc.delete(key);
		if (player.getGameMode() != 'creative' && itemStack && itemStack.hasTag('minecraft:is_pickaxe') && (itemStack.getComponent('enchantable') && !itemStack.getComponent('enchantable').hasEnchantment('silk_touch'))) { 
			block.dimension.runCommandAsync(`loot spawn ${x} ${y} ${z} loot "${loot}"`);
		}
	}
	if (player.getGameMode() != 'creative' && rng <= 50 && crop && brokenBlockPermutation.getState(crop.perm) == crop.value) {
		player.dimension.spawnEntity('minecraft:xp_orb', block.location);
	}
});
