import {world,system} from '@minecraft/server';
import {skillRequirements} from '../config.js';
import {cancelEvent,lootTable} from '../utils.js';

world.beforeEvents.itemUseOn.subscribe((e) => {
	const {itemStack,source: player,block: b,blockFace} = e;
	const {x,y,z} = b.center();
	if (itemStack) {
		const typeId = itemStack.typeId;
		const item = skillRequirements['items'][typeId];
		cancelEvent(item, player, e);
	}
	if (b) {
		const typeId = b.typeId;
		const block = skillRequirements['blocks'][typeId];
		cancelEvent(block, player, e, 'block');
	}
	const flintKnappingChance = Math.random()*100;
	const flintKnappingSuccessChance = Math.random()*100;
	const flintLoot = 'blocks/flint_shard';
	// To drop Flint Shard when Knapping Flint on stones
	if ((player['cooldown'] ?? 0) > Date.now() || !itemStack || !b || !player) return;
	if (flintKnappingChance <= 60 && flintKnappingSuccessChance <= 70 && itemStack.typeId === 'minecraft:flint' && (b.hasTag('stone') || b.hasTag('metal')) && blockFace === 'Up') {
		player['cooldown'] = Date.now() + 500;
		system.run(() => {
			itemStack.amountDecrease(player, 'Mainhand', 1);
			b.dimension.playSound("knapping.flint", b.location, {volume: 1.0});
			player.runCommandAsync(`loot spawn ${x} ${y+1} ${z} loot "${flintLoot}"`);
		});
	} else if (flintKnappingChance > 60 && flintKnappingSuccessChance <= 70 && itemStack.typeId === 'minecraft:flint' && (b.hasTag('stone') || b.hasTag('metal')) && blockFace === 'Up') {
		if (flintKnappingSuccessChance <= 50) {
			player['cooldown'] = Date.now() + 500;
			system.run(() => {
				itemStack.amountDecrease(player, 'Mainhand', 1);
				b.dimension.playSound("knapping.flint", b.location, {volume: 1.0});
			});
		} else {
			player['cooldown'] = Date.now() + 500;
			system.run(() => {
				b.dimension.playSound("knapping.flint", b.location, {volume: 1.0});
			});
		}
	}
});
