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.formatMatter
import snownee.jade.api.BlockAccessor
import snownee.jade.api.IBlockComponentProvider
import snownee.jade.api.IServerDataProvider
import snownee.jade.api.ITooltip
import snownee.jade.api.config.IPluginConfig
import snownee.jade.api.ui.BoxStyle

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

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

			matterData.putDecimal("storedMatter", it.storedMatter)
			matterData.putDecimal("maxStoredMatter", it.maxStoredMatter)

			data.put(JadeTagKeys.MATTER_STORAGE_DATA, matterData)
		}
	}

	override fun appendTooltip(tooltip: ITooltip, accessor: BlockAccessor, config: IPluginConfig) {
		val data = accessor.serverData
		if (!data.contains(JadeTagKeys.MATTER_STORAGE_DATA)) return

		val matterData = data.getCompound(JadeTagKeys.MATTER_STORAGE_DATA)
		val storedMatter = matterData.getDecimal("storedMatter")
		val maxStoredMatter = matterData.getDecimal("maxStoredMatter")

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

		tooltip.add(
			tooltip.elementHelper.progress(
				ratio,
				TranslatableComponent(
					"otm.gui.level",
					storedMatter.formatMatter(),
					maxStoredMatter.formatMatter()
				),
				style,
				BoxStyle.DEFAULT,
				true
			)
		)
	}
}
