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

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.menu.MatteryMenu
import ru.dbotthepony.mc.otm.menu.MatterySlot
import ru.dbotthepony.mc.otm.menu.UserFilteredSlot
import ru.dbotthepony.mc.otm.registry.MMenus

class CargoCrateMenu @JvmOverloads constructor(
	p_38852_: Int,
	inventory: Inventory,
	tile: CargoCrateBlockEntity? = null
) : MatteryMenu(MMenus.CARGO_CRATE, p_38852_, inventory, tile) {
	val storageSlots: List<UserFilteredSlot>

	private val trackedPlayerOpen = !inventory.player.isSpectator

	init {
		val container = tile?.container ?: SimpleContainer(CargoCrateBlockEntity.CAPACITY)

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

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

		addInventorySlots()
	}

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

		if (trackedPlayerOpen) {
			(tile as? CargoCrateBlockEntity)?.onPlayerClose()
		}
	}
}
