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

export default {
	name: "vodka",
	cookTime: cookTimeTotal,
	requiredTemp: "0",
	isValid: (inv, tempSlot) => {
		let wheatSlot = -1, potatoSlot = -1, seedsSlot = -1;
		let filled = 0;
		for (let slot = 0; slot < 4; slot++) {
			const item = inv.getItem(slot);
			if (item) {
				filled++;
				if (item.typeId === "minecraft:wheat" && wheatSlot === -1) wheatSlot = slot;
				else if (item.typeId === "minecraft:potato" && potatoSlot === -1) potatoSlot = slot;
				else if (item.typeId === "minecraft:wheat_seeds" && seedsSlot === -1) seedsSlot = 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 wheatSlot !== -1 && potatoSlot !== -1 && seedsSlot !== -1 &&
			   filled === 3 &&
			   waterValid &&
			   tankardValid &&
			   (!result || result.typeId === "brewinandchewin:vodka") &&
			   tempSlot && tempSlot.nameTag === "0";
	},
	onComplete: (inv, keg, overworld) => {
		let wheatSlot = -1, potatoSlot = -1, seedsSlot = -1;
		for (let slot = 0; slot < 4; slot++) {
			const item = inv.getItem(slot);
			if (item && item.typeId === "minecraft:wheat") wheatSlot = slot;
			if (item && item.typeId === "minecraft:potato") potatoSlot = slot;
			if (item && item.typeId === "minecraft:wheat_seeds") seedsSlot = slot;
		}
		if (wheatSlot !== -1) consumeItem(inv, wheatSlot, 1);
		if (potatoSlot !== -1) consumeItem(inv, potatoSlot, 1);
		if (seedsSlot !== -1) consumeItem(inv, seedsSlot, 1);
		
		const water = inv.getItem(liquidSlot);
		const tankard = inv.getItem(slotGen);
		let vodkaAmount = 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);
				vodkaAmount = 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:vodka", vodkaAmount);
	}
};
