package ru.dbotthepony.mc.otm.compat.jade.providers

import net.minecraft.nbt.CompoundTag
import net.minecraft.resources.ResourceLocation
import ru.dbotthepony.mc.otm.capability.MatteryCapability
import ru.dbotthepony.mc.otm.compat.jade.JadeColors
import ru.dbotthepony.mc.otm.compat.jade.JadeTagKeys
import ru.dbotthepony.mc.otm.compat.jade.JadeUids
import ru.dbotthepony.mc.otm.core.TranslatableComponent
import ru.dbotthepony.mc.otm.core.ifPresentK
import ru.dbotthepony.mc.otm.core.math.Decimal
import ru.dbotthepony.mc.otm.core.math.RGBAColor
import ru.dbotthepony.mc.otm.core.math.getDecimal
import ru.dbotthepony.mc.otm.core.math.putDecimal
import ru.dbotthepony.mc.otm.core.util.formatPower
import snownee.jade.api.*
import snownee.jade.api.config.IPluginConfig
import snownee.jade.api.ui.BoxStyle

object MatteryEnergyProvider : IBlockComponentProvider, IServerDataProvider<BlockAccessor> {
	override fun getUid(): ResourceLocation = JadeUids.MATTERY_ENERGY

	override fun appendServerData(data: CompoundTag, accessor: BlockAccessor) {
		accessor.blockEntity?.getCapability(MatteryCapability.ENERGY)?.ifPresentK {
			val energyData = CompoundTag()

			energyData.putDecimal("batteryLevel", it.batteryLevel)
			energyData.putDecimal("maxBatteryLevel", it.maxBatteryLevel)

			data.put(JadeTagKeys.MATTERY_ENERGY_DATA, energyData)
		}
	}

	override fun appendTooltip(tooltip: ITooltip, accessor: BlockAccessor, config: IPluginConfig) {
		val data = accessor.serverData

		if (!data.contains(JadeTagKeys.MATTERY_ENERGY_DATA)) return
		val energyData = data.getCompound(JadeTagKeys.MATTERY_ENERGY_DATA)

		val batteryLevel = energyData.getDecimal("batteryLevel")
		val maxBatteryLevel = energyData.getDecimal("maxBatteryLevel")

		val ratio = if (maxBatteryLevel.isZero) 0f else (batteryLevel / maxBatteryLevel).coerceIn(Decimal.ZERO, Decimal.ONE).toFloat()
		val style = tooltip.elementHelper.progressStyle()
			.color(JadeColors.ENERGY_COLOR.toARGB(), JadeColors.ENERGY_COLOR2.toARGB())
			.textColor(RGBAColor.WHITE.toARGB())

		tooltip.add(
			tooltip.elementHelper.progress(
				ratio,
				TranslatableComponent(
					"otm.gui.level",
					batteryLevel.formatPower(),
					maxBatteryLevel.formatPower()
				),
				style,
				BoxStyle.DEFAULT,
				true
			)
		)
	}
}
