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

export default {
	name: "glittering_grenadine",
	cookTime: cookTimeTotal,
	requiredTemp: "2",
	isValid: (inv, tempSlot) => {
		let inkSlot = -1, dustSlot = -1, berriesSlot = -1;
		let filled = 0;
		for (let slot = 0; slot < 4; slot++) {
			const item = inv.getItem(slot);
			if (item) {
				filled++;
				if (item.typeId === "minecraft:glow_ink_sac" && inkSlot === -1) inkSlot = slot;
				else if (item.typeId === "minecraft:glowstone_dust" && dustSlot === -1) dustSlot = slot;
				else if (item.typeId === "minecraft:glow_berries" && berriesSlot === -1) berriesSlot = 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 inkSlot !== -1 && dustSlot !== -1 && berriesSlot !== -1 &&
			   filled === 3 &&
			   waterValid &&
			   tankardValid &&
			   (!result || result.typeId === "brewinandchewin:glittering_grenadine") &&
			   tempSlot && tempSlot.nameTag === "2";
	},
	onComplete: (inv, keg, overworld) => {
		let inkSlot = -1, dustSlot = -1, berriesSlot = -1;
		for (let slot = 0; slot < 4; slot++) {
			const item = inv.getItem(slot);
			if (item && item.typeId === "minecraft:glow_ink_sac") inkSlot = slot;
			if (item && item.typeId === "minecraft:glowstone_dust") dustSlot = slot;
			if (item && item.typeId === "minecraft:glow_berries") berriesSlot = slot;
		}
		if (inkSlot !== -1) consumeItem(inv, inkSlot, 1);
		if (dustSlot !== -1) consumeItem(inv, dustSlot, 1);
		if (berriesSlot !== -1) consumeItem(inv, berriesSlot, 1);
		
		const water = inv.getItem(liquidSlot);
		const tankard = inv.getItem(slotGen);
		let grenadineAmount = 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);
				grenadineAmount = 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:glittering_grenadine", grenadineAmount);
	}
};
