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

export default {
	name: "rice_wine",
	cookTime: cookTimeTotal,
	requiredTemp: "0",
	isValid: (inv, tempSlot) => {
		let riceSlot = -1, mushroomSlot = -1;
		let filled = 0;
		for (let slot = 0; slot < 4; slot++) {
			const item = inv.getItem(slot);
			if (item) {
				filled++;
				if (item.typeId === "farmersdelight:rice" && riceSlot === -1) riceSlot = slot;
				else if (item.typeId === "minecraft:brown_mushroom" && mushroomSlot === -1) mushroomSlot = slot;
			}
		}
		const water = inv.getItem(liquidSlot);
		const tankard = inv.getItem(slotGen);
		const result = inv.getItem(resultSlot);
		const waterValid = (water && water.typeId === "minecraft:water_bucket" && water.amount >= 1) ||
						  (water && water.typeId === "minecraft:potion" && water.amount >= 1);
		const tankardValid = tankard && tankard.typeId === "brewinandchewin:tankard" &&
							((water && water.typeId === "minecraft:water_bucket" && tankard.amount >= 4) ||
							 (water && water.typeId === "minecraft:potion" && tankard.amount >= 1));
		return riceSlot !== -1 && mushroomSlot !== -1 &&
			   filled === 2 &&
			   waterValid &&
			   tankardValid &&
			   (!result || result.typeId === "brewinandchewin:rice_wine") &&
			   tempSlot && tempSlot.nameTag === "0";
	},
	onComplete: (inv, keg, overworld) => {
		let riceSlot = -1, mushroomSlot = -1;
		for (let slot = 0; slot < 4; slot++) {
			const item = inv.getItem(slot);
			if (item && item.typeId === "farmersdelight:rice") riceSlot = slot;
			if (item && item.typeId === "minecraft:brown_mushroom") mushroomSlot = slot;
		}
		if (riceSlot !== -1) consumeItem(inv, riceSlot, 1);
		if (mushroomSlot !== -1) consumeItem(inv, mushroomSlot, 1);
		
		const water = inv.getItem(liquidSlot);
		const tankard = inv.getItem(slotGen);
		let riceWineAmount = 1;
		
		if (water && water.typeId === "minecraft:water_bucket") {
			consumeItem(inv, liquidSlot, 1);
			returnTaraToBuffer(inv, "minecraft:bucket", 1);
			if (tankard && tankard.amount >= 4) {
				consumeItem(inv, slotGen, 4);
				riceWineAmount = 4;
			}
		} else if (water && water.typeId === "minecraft:potion") {
			consumeItem(inv, liquidSlot, 1);
			returnTaraToBuffer(inv, "minecraft:glass_bottle", 1);
			if (tankard) consumeItem(inv, slotGen, 1);
		}
		addResult(inv, "brewinandchewin:rice_wine", riceWineAmount);
	}
};
