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

import ru.dbotthepony.kommons.util.getValue
import ru.dbotthepony.mc.otm.capability.AbstractProfiledStorage
import ru.dbotthepony.mc.otm.capability.AbstractProfiledStorage.Companion.HISTORY_SIZE
import ru.dbotthepony.mc.otm.capability.IProfiledStorage
import ru.dbotthepony.mc.otm.capability.energy.IMatteryEnergyStorage
import ru.dbotthepony.mc.otm.capability.matter.IMatterStorage
import ru.dbotthepony.mc.otm.core.chart.DecimalHistoryChart
import ru.dbotthepony.mc.otm.core.math.Decimal
import ru.dbotthepony.mc.otm.menu.MatteryMenu
import ru.dbotthepony.mc.otm.network.StreamCodecs
import ru.dbotthepony.mc.otm.network.syncher.SynchableGroup

class ProfiledLevelGaugeWidget<P : AbstractProfiledStorage<*>>(
	synchronizer: SynchableGroup,
	val storage: P?,
	override val gauge: LevelGaugeWidget = LevelGaugeWidget(synchronizer)
) : IProfiledLevelGaugeWidget {
	constructor(
		menu: MatteryMenu,
		storage: P?,
		gauge: LevelGaugeWidget = LevelGaugeWidget(menu.mSynchronizer)
	) : this(menu.mSynchronizer, storage, gauge)

	override val received = storage?.received ?: DecimalHistoryChart(ticks = HISTORY_SIZE)
	override val transferred = storage?.transferred ?: DecimalHistoryChart(ticks = HISTORY_SIZE)

	override val receivedThisTick by synchronizer.computed({ storage?.receivedThisTick ?: Decimal.ZERO }, StreamCodecs.DECIMAL)
	override val transferredThisTick by synchronizer.computed({ storage?.transferredThisTick ?: Decimal.ZERO }, StreamCodecs.DECIMAL)

	init {
		if (storage is IMatterStorage)
			gauge.with(storage)
		else if (storage is IMatteryEnergyStorage)
			gauge.with(storage)

		synchronizer.add(received)
		synchronizer.add(transferred)
	}
}
