package ru.dbotthepony.mc.otm.menu.decorative

import com.google.common.collect.ImmutableList
import net.minecraft.server.level.ServerPlayer
import net.minecraft.world.Container
import net.minecraft.world.entity.player.Inventory
import net.minecraft.world.entity.player.Player
import net.minecraft.world.item.ItemStack
import net.minecraft.world.item.crafting.RecipeType
import net.minecraft.world.item.crafting.SingleRecipeInput
import ru.dbotthepony.kommons.util.getValue
import ru.dbotthepony.mc.otm.block.entity.decorative.GrillBlockEntity
import ru.dbotthepony.mc.otm.container.MatteryContainer
import ru.dbotthepony.mc.otm.core.immutableList
import ru.dbotthepony.mc.otm.menu.ChemicalFuelSlot
import ru.dbotthepony.mc.otm.menu.MatteryMenu
import ru.dbotthepony.mc.otm.menu.MatterySlot
import ru.dbotthepony.mc.otm.menu.makeSlots
import ru.dbotthepony.mc.otm.menu.widget.IProgressGaugeWidget
import ru.dbotthepony.mc.otm.menu.widget.TakeExperienceWidget
import ru.dbotthepony.mc.otm.registry.game.MMenus
import java.util.function.Supplier

class GrillMenu(
	containerId: Int,
	inventory: Inventory,
	tile: GrillBlockEntity? = null
) : MatteryMenu(MMenus.GRILL, containerId, inventory, tile) {
	val fuelSlot = makeSlots(tile?.fuelSlot ?: object : MatteryContainer(1) {
		override fun getMaxStackSize(): Int {
			return 4
		}
	}, ::ChemicalFuelSlot)

	val inputSlots = makeSlots<Container, MatterySlot>(tile?.inputSlots ?: object : MatteryContainer(GrillBlockEntity.SLOTS) {
		override fun getMaxStackSize(): Int {
			return 1
		}
	}) { c, i ->
		object : MatterySlot(c, i) {
			override fun onTake(p_150645_: Player, p_150646_: ItemStack) {
				super.onTake(p_150645_, p_150646_)

				if (p_150645_ is ServerPlayer)
					tile?.experience?.popExperience(p_150645_)
			}

			override fun mayPlace(itemStack: ItemStack): Boolean {
				val input = SingleRecipeInput(itemStack)
				return super.mayPlace(itemStack) && player.level().recipeManager.byType(RecipeType.SMOKING).any { it.value.matches(input, player.level()) }
			}
		}
	}

	val progress: ImmutableList<IProgressGaugeWidget.WithTicks> = immutableList(GrillBlockEntity.SLOTS) {
		object : IProgressGaugeWidget.WithTicks {
			override val isStuck: Boolean
				get() = totalTicks < workTicks
			override val workTicks: Int by mSynchronizer.computedInt(Supplier { tile?.ticksPassed(it) ?: 0 })
			override val totalTicks: Int by mSynchronizer.computedInt(Supplier { tile?.totalTicksRequired(it) ?: 0 })
		}
	}

	val fuel = object : IProgressGaugeWidget.WithTicks {
		override val isStuck: Boolean
			get() = false
		override val workTicks: Int by mSynchronizer.computedInt(Supplier { tile?.fuelTicks ?: 0 })
		override val totalTicks: Int by mSynchronizer.computedInt(Supplier { tile?.fuelTotalTicks ?: 0 })
	}

	val experience = TakeExperienceWidget(this, tile?.experience)

	init {
		addInventorySlots()
		addStorageSlot(fuelSlot)
		addStorageSlot(inputSlots)
	}
}
