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.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.menu.makeSlots
import ru.dbotthepony.mc.otm.registry.game.MMenus

class MinecartCargoCrateMenu(
	containerId: Int,
	inventory: Inventory,
	val cart: MinecartCargoCrate? = null
) : MatteryMenu(MMenus.CARGO_CRATE, containerId, inventory) {
	val actualContainer: Container = cart ?: SimpleContainer(CargoCrateBlockEntity.CAPACITY)
	val storageSlots = makeSlots(actualContainer, ::MatterySlot)

	private val trackedPlayerOpen = !inventory.player.isSpectator

	val sort = SortInput(actualContainer, playerSortSettings)

	init {
		if (trackedPlayerOpen) {
			cart?.onPlayerOpen(inventory.player)
		}

		addStorageSlot(storageSlots)
		addInventorySlots()
	}

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

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

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