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

import net.minecraft.core.BlockPos
import net.minecraft.world.level.block.entity.BlockEntityType
import net.minecraft.world.level.block.state.BlockState
import ru.dbotthepony.mc.otm.capability.energy
import ru.dbotthepony.mc.otm.capability.energy.IMatteryEnergyStorage
import ru.dbotthepony.mc.otm.capability.extractEnergy
import ru.dbotthepony.mc.otm.container.HandlerFilter
import ru.dbotthepony.mc.otm.container.MatteryContainer
import ru.dbotthepony.mc.otm.core.math.Decimal

abstract class MatteryPoweredBlockEntity(p_155228_: BlockEntityType<*>, p_155229_: BlockPos, p_155230_: BlockState) : MatteryDeviceBlockEntity(p_155228_, p_155229_, p_155230_) {
	val batteryContainer = MatteryContainer(::markDirtyFast, 1).also(::addDroppableContainer)
	val batteryItemHandler = batteryContainer.handler(HandlerFilter.Dischargeable)
	open val energy: IMatteryEnergyStorage?
		get() = null

	init {
		savetables.stateful(::batteryContainer, BATTERY_KEY)
	}

	override fun tick() {
		super.tick()

		if (batteryContainer.isEmpty) return

		val energy = energy ?: return
		var demand = energy.receiveEnergy(energy.missingPower, true)
		if (demand.isZero) return

		for (stack in batteryContainer) {
			stack.energy?.let {
				val diff = it.extractEnergy(demand, false)
				energy.receiveEnergy(diff, false)
				demand -= diff
			}

			if (demand <= Decimal.ZERO)
				return
		}
	}
}
