import { world,system,BlockPermutation,ItemStack} from "@minecraft/server";
import {axes,shovels,hoes} from '../config.js';
import '../utils.js';

// Handles durability dmg on custom tools use on block
world.beforeEvents.playerInteractWithBlock.subscribe(event => {
	const {blockFace,block,itemStack,player} = event;
	if ((player['cooldown'] ?? 0) > Date.now()) return;
	const location = block.center();
	location.y += 0.6;
	if (!itemStack && blockFace == 'Up' && player.isSneaking && player.getProperty("vb:backpack_type") !== "none") {
		player.runCommandAsync(`/tp @e[type=vb:backpack,tag=on_shoulder,c=1] ${location.x} ${location.y} ${location.z} facing @a[c=1]`);
	}
	if (itemStack && itemStack.hasTag('minecraft:is_axe')) {
		if (block.typeId.includes('stripped')) return;
		const sound = itemStack.hasTag('minecraft:is_battleaxe') ? 'scrape' : 'dig.wood';
		if (axes.includes(itemStack.typeId) && block.typeId.includes('log')) {
			system.run(() => {
				itemStack.durabilityModifier(player, 'Mainhand', 1);
				player.dimension.playSound(sound, block.location);
			});
			player['cooldown'] = Date.now() + 500;
		}
	}
	if (itemStack && itemStack.hasTag('minecraft:is_shovel')) {
		if (shovels.includes(itemStack.typeId) && block.above().isAir == true && (block.typeId == 'minecraft:grass_block' || block.typeId == 'minecraft:dirt_with_roots' || block.typeId == 'minecraft:mycelium' || block.typeId == 'minecraft:podzol' || block.typeId == 'minecraft:coarse_dirt' || block.typeId == 'minecraft:dirt')) {
			system.run(() => {
				itemStack.durabilityModifier(player, 'Mainhand', 1);
				player.dimension.playSound('hit.grass', block.location);
			});
			player['cooldown'] = Date.now() + 500;
		}
		else if (shovels.includes(itemStack.typeId) && block.above().isAir == true && block.typeId == 'minecraft:snow_layer') {
			system.run(() => {
				itemStack.durabilityModifier(player, 'Mainhand', 1);
				block.dimension.spawnItem(new ItemStack('minecraft:snowball'), block.location);
				player.dimension.playSound('hit.grass', block.location);
			});
			player['cooldown'] = Date.now() + 500;
		}
	}
	if (itemStack && itemStack.hasTag('minecraft:is_hoe')) {
		if (hoes.includes(itemStack.typeId) && block.above().isAir == true && (block.typeId == 'minecraft:grass_block' || block.typeId == 'minecraft:grass_path' || block.typeId == 'minecraft:dirt')) {
			system.run(() => {
				itemStack.durabilityModifier(player, 'Mainhand', 1);
				player.dimension.playSound('hit.gravel', block.location);
			});
			player['cooldown'] = Date.now() + 500;
		}
	}
});
