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

import mezz.jei.api.constants.VanillaTypes
import mezz.jei.api.gui.builder.IRecipeLayoutBuilder
import mezz.jei.api.gui.drawable.IDrawable
import mezz.jei.api.recipe.IFocusGroup
import mezz.jei.api.recipe.RecipeIngredientRole
import mezz.jei.api.recipe.RecipeType
import mezz.jei.api.recipe.category.IRecipeCategory
import net.minecraft.client.gui.GuiGraphics
import net.minecraft.network.chat.Component
import net.minecraft.resources.ResourceLocation
import net.minecraft.world.item.ItemStack
import net.minecraft.world.item.Items
import net.minecraft.world.item.crafting.Ingredient
import ru.dbotthepony.mc.otm.OverdriveThatMatters
import ru.dbotthepony.mc.otm.client.render.MGUIGraphics
import ru.dbotthepony.mc.otm.client.render.ItemStackIcon
import ru.dbotthepony.mc.otm.client.screen.panels.slot.AbstractSlotPanel
import ru.dbotthepony.mc.otm.client.screen.widget.ProgressGaugePanel
import ru.dbotthepony.mc.otm.recipe.PainterRecipe
import ru.dbotthepony.mc.otm.registry.MItems
import ru.dbotthepony.mc.otm.registry.MNames

object PainterRecipeCategory : IRecipeCategory<PainterRecipe>, IDrawable {
	private val type = RecipeType(ResourceLocation(OverdriveThatMatters.MOD_ID, MNames.PAINTER), PainterRecipe::class.java)

	override fun getRecipeType(): RecipeType<PainterRecipe> {
		return type
	}

	override fun getTitle(): Component {
		return MItems.PAINTER.description
	}

	override fun getBackground(): IDrawable {
		return this
	}

	override fun getWidth(): Int {
		return 120
	}

	override fun getHeight(): Int {
		return 56
	}

	private val icon = IGUIRenderable2IDrawable(ItemStackIcon(ItemStack(MItems.PAINTER)))

	override fun getIcon(): IDrawable {
		return icon
	}

	override fun setRecipe(builder: IRecipeLayoutBuilder, recipe: PainterRecipe, focuses: IFocusGroup) {
		var x = 0
		var y = 0

		for ((dye, count) in recipe.dyes) {
			builder.addSlot(RecipeIngredientRole.CATALYST, 1 + x * 18, 1 + y * 18)
				.addIngredients(VanillaTypes.ITEM_STACK, dye?.let { Ingredient.of(it.tag).items.map { it.copyWithCount(count) } } ?: listOf(ItemStack(Items.WATER_BUCKET, count)))

			y++

			if (y >= 3) {
				x++
				y = 0
			}
		}

		builder.addSlot(RecipeIngredientRole.INPUT, 50, 22).addIngredients(recipe.input)
		builder.addSlot(RecipeIngredientRole.OUTPUT, 100, 22).addIngredients(VanillaTypes.ITEM_STACK, listOf(recipe.output))
	}

	override fun draw(guiGraphics: GuiGraphics, xOffset: Int, yOffset: Int) {
		val wrap = MGUIGraphics(guiGraphics)

		for (x in 0 .. 1) {
			for (y in 0 .. 2) {
				AbstractSlotPanel.SLOT_BACKGROUND.render(wrap, xOffset.toFloat() + x * 18f, yOffset.toFloat() + y * 18f)
			}
		}

		AbstractSlotPanel.SLOT_BACKGROUND.render(wrap, xOffset.toFloat() + 49f, yOffset.toFloat() + 21f)
		AbstractSlotPanel.SLOT_BACKGROUND.render(wrap, xOffset.toFloat() + 99f, yOffset.toFloat() + 21f)

		ProgressGaugePanel.GAUGE_BACKGROUND.render(wrap, xOffset.toFloat() + 73f, yOffset.toFloat() + 22f)
	}
}
