import { EquipmentSlot, ItemStack } from '@minecraft/server';
import { itemApplyDamage, spawnEntityRotatedByBlock } from '../util/utils';
import { equipEntityWithItem } from './Global'
import { directionState } from '../util/globalVariables';

export class McfChoppingBoard {
	constructor() {
		this.itemList = {
			"minecraft:bread": { result: "mr:bread_slice", amount: 6 }
		};
		this.onPlayerInteract = this.onPlayerInteract.bind(this);
	}
	onPlayerInteract(e) {
		const { player, block, dimension } = e;
		const item = player.getComponent("equippable")?.getEquipment(EquipmentSlot.Mainhand);
		if (!item) return;
		const cuttable = this.itemList[item.typeId];
		const foodEntity = dimension.getEntitiesAtBlockLocation(block.location).find(en => en.matches({ type: "mr:item_placer" }));
		const location = block.bottomCenter();
		if (!foodEntity && cuttable) {
			const direction = block.permutation.getState(directionState);
			const cuttableFood = spawnEntityRotatedByBlock("mr:item_placer", block, direction, { init: location });
			equipEntityWithItem(player, cuttableFood, item.typeId);
			cuttableFood.setDynamicProperty("mr:food_result", cuttable.result);
			cuttableFood.setDynamicProperty("mr:food_amount", cuttable.amount);
			return;
		}
		if (foodEntity && item.hasTag("mc:is_knife")) {
			dimension.spawnItem(new ItemStack(foodEntity.getDynamicProperty("mr:food_result"), foodEntity.getDynamicProperty("mr:food_amount")), location);
			itemApplyDamage(player, item);
			dimension.playSound("mcf.knife_chop", location);
			foodEntity.remove();
		}
	}
}