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

import net.minecraft.core.BlockPos
import net.minecraft.server.level.ServerLevel
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.Block
import net.minecraft.world.level.block.state.BlockState
import ru.dbotthepony.mc.otm.OverdriveThatMatters
import ru.dbotthepony.mc.otm.block.entity.MatteryPoweredBlockEntity
import ru.dbotthepony.mc.otm.block.storage.DriveViewerBlock
import ru.dbotthepony.mc.otm.block.entity.WorkerState
import ru.dbotthepony.mc.otm.capability.MatteryCapability
import ru.dbotthepony.mc.otm.capability.energy.WorkerEnergyStorage
import ru.dbotthepony.mc.otm.config.MachinesConfig
import ru.dbotthepony.mc.otm.container.MatteryContainer
import ru.dbotthepony.mc.otm.registry.MBlockEntities
import ru.dbotthepony.mc.otm.menu.storage.DriveViewerMenu

class DriveViewerBlockEntity(p_155229_: BlockPos, p_155230_: BlockState) : MatteryPoweredBlockEntity(MBlockEntities.DRIVE_VIEWER, p_155229_, p_155230_) {
	override fun setChanged() {
		super.setChanged()

		val level = level
		if (level is ServerLevel)
			tickList.once {
				var state = blockState

				if (container.getItem(0).getCapability(MatteryCapability.DRIVE).isPresent && energy.batteryLevel >= OverdriveThatMatters.INSTANCE.ITEM_STORAGE().energyPerOperation) {
					state = state.setValue(WorkerState.SEMI_WORKER_STATE, WorkerState.WORKING)
				} else {
					state = state.setValue(WorkerState.SEMI_WORKER_STATE, WorkerState.IDLE)
				}

				if (state !== blockState) {
					level.setBlock(blockPos, state, Block.UPDATE_CLIENTS)
				}
			}
	}

	val energy = WorkerEnergyStorage(this, MachinesConfig.DRIVE_VIEWER)

	val container: MatteryContainer = object : MatteryContainer(this::setChanged, 1) {
		override fun setChanged(slot: Int, new: ItemStack, old: ItemStack) {
			super.setChanged(slot, new, old)

			val level = level

			if (level is ServerLevel)
				tickList.once {
					if (!isRemoved) {
						var state = blockState

						if (new.getCapability(MatteryCapability.DRIVE).isPresent) {
							state = state.setValue(DriveViewerBlock.DRIVE_PRESENT, true)
						} else {
							state = state.setValue(DriveViewerBlock.DRIVE_PRESENT, false)
						}

						if (state !== blockState) {
							level.setBlock(blockPos, state, Block.UPDATE_CLIENTS)
						}
					}
				}
		}
	}.also(::addDroppableContainer)

	init {
		savetable(::energy, ENERGY_KEY)
		savetable(::container, INVENTORY_KEY)

		exposeEnergyGlobally(energy)
	}

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