import { world, BlockPermutation, Direction, EntityDamageCause, EquipmentSlot, GameMode, ItemStack } from "@minecraft/server";

export function blockSlabPlace(block,itemStack,player,blockId,interactBlocks) {
	const itemStackId = itemStack.typeId;
	const center = block.center();
	for (const{matches,sound="dig.stone",pitch=0.8+Math.random()*0.2,volume=1.0} of interactBlocks) {
		if (matches(blockId,block)) {
			interactBlockSlab(player,itemStack);
			const soundId = typeof sound=="function"?sound(blockId):sound;
			const pitchRange = typeof pitch=="function"?pitch():pitch;
			const volumeRange = typeof volume=="function"?volume():volume;
			player.playSound(soundId,{location:center,pitch:pitchRange,volume:volumeRange});
			return true;
		}
	}
	return false;
};

export function interactBlockSlab(player,itemStack) {
	const item = player.getComponent("minecraft:equippable").getEquipmentSlot(EquipmentSlot.Mainhand);
	if (player.getGameMode()==GameMode.Creative) return;
	if (item.amount>1) item.amount--;
	else item.setItem(undefined);
};

export function interactDamageTool(durability,enchantable,mainhand,player,itemStack) {
	if (player.getGameMode()==GameMode.Creative) return;
	const unbreaking = enchantable?.getEnchantment("unbreaking")?.level;
	const damageChance = 1/(unbreaking+1);
	if (Math.random()>damageChance) return;
	if (durability.damage>=durability.maxDurability) {
		mainhand.setItem(undefined);
		player.playSound("random.break");
	}
	else {
		durability.damage++;
		mainhand.setItem(itemStack);
	}
};

export function interactToolUse(block,itemStack,player,interactBlocks) {
	const mainhand = player.getComponent("minecraft:equippable").getEquipmentSlot(EquipmentSlot.Mainhand);
	const durability = itemStack.getComponent("minecraft:durability");
	const enchantable = itemStack.getComponent("minecraft:enchantable");
	const blockId = block.typeId;
	const center = block.center();
	for (const{matches,sound="use.stone",pitch=1.0,volume=1.0} of interactBlocks) {
		if (matches(blockId,block)) {
			interactDamageTool(durability,enchantable,mainhand,player,itemStack);
			const soundId = typeof sound=="function"?sound(blockId):sound;
			const pitchRange = typeof pitch=="function"?pitch():pitch;
			const volumeRange = typeof volume=="function"?volume():volume;
			player.playSound(soundId,{location:center,pitch:pitchRange,volume:volumeRange});
			return true;
		}
	}
	return false;
};