package ru.dbotthepony.mc.otm.compat.jei

import mezz.jei.api.ingredients.IIngredientType
import mezz.jei.api.ingredients.ITypedIngredient
import mezz.jei.api.runtime.IClickableIngredient
import net.minecraft.client.renderer.Rect2i
import ru.dbotthepony.mc.otm.client.screen.panels.EditablePanel
import ru.dbotthepony.mc.otm.core.filterNotNull
import java.util.*

class Panel2ClickableIngredient<P : EditablePanel<*>, T>(val panel: P, val ingredient: ITypedIngredient<T>) : IClickableIngredient<T> {
	override fun getTypedIngredient(): ITypedIngredient<T> {
		return ingredient
	}

	override fun getArea(): Rect2i {
		return panel.calculateAbsoluteRectangle().toIntRect()
	}

	companion object {
		inline fun <reified P : EditablePanel<*>, T : Any> find(mouseX: Double, mouseY: Double, type: IIngredientType<T>, source: Collection<EditablePanel<*>>, noinline provider: (P) -> T): Optional<IClickableIngredient<*>> {
			return source
				.stream()
				.map { it.panelOfTypeUnderCursor<P>(mouseX.toFloat(), mouseY.toFloat(), ignoreMouseInputLock = true) }
				.filter { it.interrupt }
				.findFirst()
				.flatMap { Optional.ofNullable(it.panel) }
				.flatMap { a -> JEIPlugin.helpers.ingredientManager.createTypedIngredient(type, provider(a)).map { a to it } }
				.map { Panel2ClickableIngredient(it.first!!, it.second) }
		}
	}
}
