import { resultSlot, liquidSlot } from "./helpers.js";
import { cookTimeTotal } from "./helpers.js";
import { consumeItem, addResult, returnTaraToBuffer } from "./helpers.js";

export default {
	name: "cocoa_fudge",
	cookTime: cookTimeTotal,
	requiredTemp: "2",
	isValid: (inv, tempSlot) => {
		let cocoaSlots = [];
		let sugarSlot = -1;
		let filled = 0;
		for (let slot = 0; slot < 4; slot++) {
			const item = inv.getItem(slot);
			if (item) {
				filled++;
				if (item.typeId === "minecraft:cocoa_beans" && cocoaSlots.length < 2) {
					cocoaSlots.push(slot);
				} else if (item.typeId === "minecraft:sugar" && sugarSlot === -1) {
					sugarSlot = slot;
				}
			}
		}
		const milk = inv.getItem(liquidSlot);
		const result = inv.getItem(resultSlot);
		return cocoaSlots.length === 2 &&
			   sugarSlot !== -1 &&
			   filled === 3 &&
			   milk && milk.typeId === "farmersdelight:milk_bottle" && milk.amount >= 2 &&
			   !inv.getItem(6) &&
			   (!result || result.typeId === "brewinandchewin:cocoa_fudge") &&
			   tempSlot && tempSlot.nameTag === "2";
	},
	onComplete: (inv, keg, overworld) => {
		let cocoaSlots = [];
		let sugarSlot = -1;
		for (let slot = 0; slot < 4; slot++) {
			const item = inv.getItem(slot);
			if (item && item.typeId === "minecraft:cocoa_beans") cocoaSlots.push(slot);
			if (item && item.typeId === "minecraft:sugar") sugarSlot = slot;
		}
		for (const slot of cocoaSlots) consumeItem(inv, slot, 1);
		if (sugarSlot !== -1) consumeItem(inv, sugarSlot, 1);
		const milk = inv.getItem(liquidSlot);
		if (milk) {
			consumeItem(inv, liquidSlot, 2);
			returnTaraToBuffer(inv, "minecraft:glass_bottle", 2);
		}
		addResult(inv, "brewinandchewin:cocoa_fudge", 1);
	}
};
