package ru.dbotthepony.mc.otm.recipe

import net.minecraft.world.item.crafting.CraftingInput
import net.minecraft.world.item.crafting.Ingredient
import net.minecraft.world.item.crafting.ShapedRecipePattern
import ru.dbotthepony.mc.otm.core.get
import ru.dbotthepony.mc.otm.core.isNotEmpty

val ShapedRecipePattern.isIncomplete: Boolean
	get() = ingredients().any { it.items.size == 1 && it.hasNoItems() }

val ShapedRecipePattern.width: Int get() = width()
val ShapedRecipePattern.height: Int get() = height()

operator fun ShapedRecipePattern.get(column: Int, row: Int): Ingredient {
	return ingredients()[column + row * width]
}

fun ShapedRecipePattern.preemptiveTest(t: CraftingInput.Positioned, craftingWidth: Int, craftingHeight: Int): Boolean {
	if (
		t.input.width() > width ||
		t.input.height() > height
	) {
		return false
	}

	for (columnPadding in 0 .. craftingWidth - width) {
		for (rowPadding in 0 .. craftingHeight - height) {
			var invalid = false

			outer@for (column in 0 until width) {
				for (row in 0 until height) {
					val ingredient = this[column, row]
					val item = t[column + columnPadding, row + rowPadding]

					if (!ingredient.test(item) && item.isNotEmpty) {
						invalid = true
						break@outer
					}
				}
			}

			if (!invalid) {
				return true
			}
		}
	}

	return false
}

fun ShapedRecipePattern.test(t: CraftingInput): Boolean {
	if (t.width() != width || t.height() != height)
		return false

	for (column in 0 until width)
		for (row in 0 until height)
			if (!this[column, row].test(t[column, row]))
				return false

	return true
}
