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

import net.minecraft.core.BlockPos
import net.minecraft.server.level.ServerPlayer
import net.minecraft.world.entity.player.Inventory
import net.minecraft.world.entity.player.Player
import net.minecraft.world.inventory.AbstractContainerMenu
import net.minecraft.world.item.ItemStack
import net.minecraft.world.level.block.state.BlockState
import ru.dbotthepony.mc.otm.block.entity.MatteryDeviceBlockEntity
import ru.dbotthepony.mc.otm.container.HandlerFilter
import ru.dbotthepony.mc.otm.container.MatteryContainer
import ru.dbotthepony.mc.otm.item.EssenceCapsuleItem
import ru.dbotthepony.mc.otm.menu.tech.EssenceStorageMenu
import ru.dbotthepony.mc.otm.registry.MBlockEntities

class EssenceStorageBlockEntity(blockPos: BlockPos, blockState: BlockState) : MatteryDeviceBlockEntity(MBlockEntities.ESSENCE_STORAGE, blockPos, blockState) {
	var experienceStored = 0L
		set(value) {
			require(value >= 0L) { "Negative experience: $value" }
			field = value
			setChangedLight()
		}

	val capsuleContainer = MatteryContainer(::setChangedLight, 1)
	val servoContainer = MatteryContainer(::setChangedLight, 1)

	init {
		savetables.long(::experienceStored)
		savetables.stateful(::capsuleContainer)
		savetables.stateful(::servoContainer)
	}

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

	val itemConfig = ConfigurableItemHandler(
		input = capsuleContainer.handler(HandlerFilter.OnlyIn.and(object : HandlerFilter {
			override fun canInsert(slot: Int, stack: ItemStack): Boolean {
				return stack.item is EssenceCapsuleItem
			}
		}))
	)

	override fun tick() {
		super.tick()

		if (!redstoneControl.isBlockedByRedstone) {
			val capsule = capsuleContainer[0]

			if (!capsule.isEmpty && capsule.item is EssenceCapsuleItem) {
				experienceStored += EssenceCapsuleItem.experienceStored(capsule)
				capsuleContainer.clearContent()
			}
		}
	}
}
