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

export default {
	name: "egg_grog",
	cookTime: cookTimeTotal,
	requiredTemp: "0",
	isValid: (inv, tempSlot) => {
		let eggSlot = -1, sugarSlot = -1, cabbageSlot = -1;
		let filled = 0;
		for (let slot = 0; slot < 4; slot++) {
			const item = inv.getItem(slot);
			if (item) {
				filled++;
				if (item.typeId === "minecraft:egg" && eggSlot === -1) eggSlot = slot;
				else if (item.typeId === "minecraft:sugar" && sugarSlot === -1) sugarSlot = slot;
				else if ((item.typeId === "farmersdelight:cabbage" || item.typeId === "farmersdelight:cabbage_leaf") && cabbageSlot === -1) cabbageSlot = slot;
			}
		}
		const milk = inv.getItem(liquidSlot);
		const tankard = inv.getItem(slotGen);
		const result = inv.getItem(resultSlot);
		const milkValid = (milk && milk.typeId === "minecraft:milk_bucket" && milk.amount >= 1) ||
						 (milk && milk.typeId === "farmersdelight:milk_bottle" && milk.amount >= 1);
		const tankardValid = tankard && tankard.typeId === "brewinandchewin:tankard" &&
							((milk && milk.typeId === "minecraft:milk_bucket" && tankard.amount >= 4) ||
							 (milk && milk.typeId === "farmersdelight:milk_bottle" && tankard.amount >= 1));
		return eggSlot !== -1 && sugarSlot !== -1 && cabbageSlot !== -1 &&
			   filled === 3 &&
			   milkValid &&
			   tankardValid &&
			   (!result || result.typeId === "brewinandchewin:egg_grog") &&
			   tempSlot && tempSlot.nameTag === "0";
	},
	onComplete: (inv, keg, overworld) => {
		let eggSlot = -1, sugarSlot = -1, cabbageSlot = -1;
		for (let slot = 0; slot < 4; slot++) {
			const item = inv.getItem(slot);
			if (item && item.typeId === "minecraft:egg") eggSlot = slot;
			if (item && item.typeId === "minecraft:sugar") sugarSlot = slot;
			if (item && (item.typeId === "farmersdelight:cabbage" || item.typeId === "farmersdelight:cabbage_leaf")) cabbageSlot = slot;
		}
		if (eggSlot !== -1) consumeItem(inv, eggSlot, 1);
		if (sugarSlot !== -1) consumeItem(inv, sugarSlot, 1);
		if (cabbageSlot !== -1) consumeItem(inv, cabbageSlot, 1);
		
		const milk = inv.getItem(liquidSlot);
		const tankard = inv.getItem(slotGen);
		let eggGrogAmount = 1;
		
		if (milk && milk.typeId === "minecraft:milk_bucket") {
			consumeItem(inv, liquidSlot, 1);
			returnTaraToBuffer(inv, "minecraft:bucket", 1);
			if (tankard && tankard.amount >= 4) {
				consumeItem(inv, slotGen, 4);
				eggGrogAmount = 4;
			}
		} else if (milk && milk.typeId === "farmersdelight:milk_bottle") {
			consumeItem(inv, liquidSlot, 4);
			returnTaraToBuffer(inv, "minecraft:glass_bottle", 4);
			if (tankard) consumeItem(inv, slotGen, 1);
		}
		addResult(inv, "brewinandchewin:egg_grog", eggGrogAmount);
	}
};
