package ru.dbotthepony.mc.otm.menu.widget

import net.neoforged.neoforge.fluids.FluidStack
import net.neoforged.neoforge.fluids.capability.IFluidHandler
import ru.dbotthepony.mc.otm.network.syncher.SynchableGroup
import ru.dbotthepony.kommons.util.getValue
import ru.dbotthepony.mc.otm.container.get
import ru.dbotthepony.mc.otm.menu.MatteryMenu
import ru.dbotthepony.mc.otm.network.wrap
import java.util.function.IntSupplier
import java.util.function.Supplier

class FluidGaugeWidget(synchronizer: SynchableGroup) {
	constructor(menu: MatteryMenu) : this(menu.mSynchronizer)

	var maxCapacitySupplier = IntSupplier { 0 }
	var fluidSupplier = Supplier { FluidStack.EMPTY }

	val maxCapacity by synchronizer.computedInt(IntSupplier { maxCapacitySupplier.asInt })
	val fluid by synchronizer.computed({ fluidSupplier.get() }, FluidStack.OPTIONAL_STREAM_CODEC.wrap())

	val percentage: Float get() {
		if (maxCapacity <= 0 || fluid.isEmpty) {
			return 0f
		}

		return (fluid.amount.toFloat() / maxCapacity.toFloat()).coerceIn(0f, 1f)
	}

	constructor(synchronizer: SynchableGroup, fluid: IFluidHandler?, tank: Int = 0) : this(synchronizer) {
		if (fluid != null) {
			with(fluid, tank)
		}
	}

	constructor(menu: MatteryMenu, fluid: IFluidHandler?, tank: Int = 0) : this(menu) {
		if (fluid != null) {
			with(fluid, tank)
		}
	}

	fun with(fluid: IFluidHandler, tank: Int = 0): FluidGaugeWidget {
		maxCapacitySupplier = IntSupplier { fluid.getTankCapacity(tank) }
		fluidSupplier = Supplier { fluid[tank] }
		return this
	}
}
