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

import net.minecraft.world.Container
import net.minecraft.world.SimpleContainer
import net.minecraft.world.entity.player.Inventory
import net.minecraft.world.entity.player.Player
import ru.dbotthepony.mc.otm.core.immutableList
import ru.dbotthepony.mc.otm.block.entity.decorative.CargoCrateBlockEntity
import ru.dbotthepony.mc.otm.entity.MinecartCargoCrate
import ru.dbotthepony.mc.otm.menu.MatteryMenu
import ru.dbotthepony.mc.otm.menu.MatterySlot
import ru.dbotthepony.mc.otm.registry.MMenus

class MinecartCargoCrateMenu @JvmOverloads constructor(
	p_38852_: Int,
	inventory: Inventory,
	val cart: MinecartCargoCrate? = null
) : MatteryMenu(MMenus.CARGO_CRATE, p_38852_, inventory) {
	val storageSlots: List<MatterySlot>

	private val trackedPlayerOpen = !inventory.player.isSpectator

	init {
		val container = cart as Container? ?: SimpleContainer(CargoCrateBlockEntity.CAPACITY)

		storageSlots = immutableList(CargoCrateBlockEntity.CAPACITY) {
			addStorageSlot(MatterySlot(container, it))
		}

		if (trackedPlayerOpen) {
			cart?.onPlayerOpen()
		}

		addInventorySlots()
	}

	override fun removed(p_38940_: Player) {
		super.removed(p_38940_)

		if (trackedPlayerOpen) {
			cart?.onPlayerClose()
		}
	}

	override fun stillValid(player: Player): Boolean {
		return cart?.stillValid(player) ?: true
	}
}
