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

import net.minecraftforge.fluids.FluidStack
import net.minecraftforge.fluids.capability.IFluidHandler
import ru.dbotthepony.mc.otm.container.get
import ru.dbotthepony.mc.otm.core.util.FluidStackValueCodec
import ru.dbotthepony.mc.otm.menu.MatteryMenu
import ru.dbotthepony.mc.otm.network.synchronizer.FieldSynchronizer
import java.util.function.IntSupplier
import java.util.function.Supplier

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

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

	val maxCapacity by synchronizer.ComputedIntField({ maxCapacitySupplier.asInt })
	val fluid by synchronizer.ComputedField({ fluidSupplier.get() }, FluidStackValueCodec)

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

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

	constructor(synchronizer: FieldSynchronizer, 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
	}
}
