package ru.dbotthepony.mc.otm.block.entity.tech

import net.minecraft.core.BlockPos
import net.minecraft.world.entity.player.Inventory
import net.minecraft.world.entity.player.Player
import net.minecraft.world.inventory.AbstractContainerMenu
import net.minecraft.world.level.block.entity.BlockEntityType
import net.minecraft.world.level.block.state.BlockState
import net.neoforged.neoforge.capabilities.Capabilities
import ru.dbotthepony.mc.otm.block.entity.MatteryDeviceBlockEntity
import ru.dbotthepony.mc.otm.block.entity.decorative.CargoCrateBlockEntity
import ru.dbotthepony.mc.otm.container.HandlerFilter
import ru.dbotthepony.mc.otm.container.MatteryContainer
import ru.dbotthepony.mc.otm.core.multiblock.BlockEntityTag
import ru.dbotthepony.mc.otm.menu.tech.ItemHatchMenu
import ru.dbotthepony.mc.otm.registry.game.MBlockEntities

class ItemHatchBlockEntity(
	val isInput: Boolean,
	type: BlockEntityType<*>,
	blockPos: BlockPos,
	blockState: BlockState
) : MatteryDeviceBlockEntity(type, blockPos, blockState) {
	val container = MatteryContainer(this::markDirtyFast, CAPACITY).also(::addDroppableContainer)
	val itemHandler = container.handler(if (isInput) HandlerFilter.OnlyIn else HandlerFilter.OnlyOut)

	init {
		savetables.stateful(::container, INVENTORY_KEY)
		exposeGlobally(Capabilities.ItemHandler.BLOCK, itemHandler)
	}

	override fun createMenu(containerID: Int, inventory: Inventory, ply: Player): AbstractContainerMenu {
		return ItemHatchMenu(isInput, containerID, inventory, this)
	}

	companion object {
		const val CAPACITY = CargoCrateBlockEntity.CAPACITY

		val INPUT_TAG = BlockEntityTag(ItemHatchBlockEntity::class) { it.isInput }
		val OUTPUT_TAG = BlockEntityTag(ItemHatchBlockEntity::class) { !it.isInput }

		fun input(blockPos: BlockPos, blockState: BlockState): ItemHatchBlockEntity {
			return ItemHatchBlockEntity(true, MBlockEntities.ITEM_INPUT_HATCH, blockPos, blockState)
		}

		fun output(blockPos: BlockPos, blockState: BlockState): ItemHatchBlockEntity {
			return ItemHatchBlockEntity(false, MBlockEntities.ITEM_OUTPUT_HATCH, blockPos, blockState)
		}
	}
}
