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

export default {
	name: "kimchi",
	cookTime: cookTimeTotal,
	requiredTemp: "3",
	isValid: (inv, tempSlot) => {
		let kelpSlot = -1;
		let veggieSlots = [];
		let onlyVegOrEmpty = true;
		let filled = 0;
		let hasCabbage = false;
		let hasCabbageLeaf = false;
		let cabbageSlot = -1;
		let cabbageLeafSlot = -1;
		for (let slot = 0; slot < 4; slot++) {
			const item = inv.getItem(slot);
			if (item) {
				filled++;
				if (item.typeId === "minecraft:kelp" && kelpSlot === -1) {
					kelpSlot = slot;
				} else if (item.typeId === "farmersdelight:cabbage" && cabbageSlot === -1) {
					hasCabbage = true;
					cabbageSlot = slot;
					veggieSlots.push(slot);
				} else if (item.typeId === "farmersdelight:cabbage_leaf" && cabbageLeafSlot === -1) {
					hasCabbageLeaf = true;
					cabbageLeafSlot = slot;
					veggieSlots.push(slot);
				} else if (allowedVeggies.includes(item.typeId)) {
					veggieSlots.push(slot);
				} else {
					onlyVegOrEmpty = false;
					break;
				}
			}
		}
		if (!onlyVegOrEmpty || filled !== 3 || kelpSlot === -1) return false;
		if (hasCabbage && hasCabbageLeaf) return false;
		if (hasCabbage && veggieSlots.some(slot => slot !== cabbageSlot && inv.getItem(slot).typeId === "farmersdelight:cabbage_leaf")) return false;
		if (hasCabbageLeaf && veggieSlots.some(slot => slot !== cabbageLeafSlot && inv.getItem(slot).typeId === "farmersdelight:cabbage")) return false;
		
		const result = inv.getItem(resultSlot);
		return (!inv.getItem(liquidSlot) && !inv.getItem(6)) &&
			   (!result || result.typeId === "brewinandchewin:kimchi") &&
			   tempSlot && tempSlot.nameTag === "3";
	},
	onComplete: (inv, keg, overworld) => {
		let slotsToSpend = [];
		for (let slot = 0; slot < 4; slot++) {
			const item = inv.getItem(slot);
			if (item && (item.typeId === "minecraft:kelp" || allowedVeggies.includes(item.typeId))) {
				slotsToSpend.push(slot);
			}
		}
		for (const slot of slotsToSpend) {
			consumeItem(inv, slot, 1);
		}
		addResult(inv, "brewinandchewin:kimchi", 2);
	}
};
