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

import net.minecraft.nbt.CompoundTag
import net.minecraft.resources.ResourceLocation
import ru.dbotthepony.mc.otm.block.entity.matter.MatterReconstructorBlockEntity
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.math.RGBAColor
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 MatterReconstructorProvider : IBlockComponentProvider, IServerDataProvider<BlockAccessor> {
	override fun getUid(): ResourceLocation = JadeUids.MATTER_RECONSTRUCTOR

	override fun appendServerData(data: CompoundTag, accessor: BlockAccessor) {
		if (accessor.blockEntity is MatterReconstructorBlockEntity) {
			val reconstructor = accessor.blockEntity as MatterReconstructorBlockEntity

			val item = reconstructor.repairContainer.get(0)

			if (!item.isEmpty && item.isDamageableItem && item.maxDamage != 0) {
				val reconstructorData = CompoundTag()

				reconstructorData.putInt("damage", item.maxDamage - item.damageValue)
				reconstructorData.putInt("maxDamage", item.maxDamage)

				data.put(JadeTagKeys.MATTER_RECONSTRUCTOR_DATA, reconstructorData)
			}
		}
	}

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

		if (!data.contains(JadeTagKeys.MATTER_RECONSTRUCTOR_DATA)) return
		val reconstructorData = data.getCompound(JadeTagKeys.MATTER_RECONSTRUCTOR_DATA)

		val damage = reconstructorData.getInt("damage")
		val maxDamage = reconstructorData.getInt("maxDamage")

		val ratio = damage.toFloat() / maxDamage.toFloat()

		tooltip.add(
			tooltip.elementHelper.progress(
				ratio,
				TranslatableComponent(
					"item.durability",
					damage,
					maxDamage
				),
				tooltip.elementHelper.progressStyle().color(RGBAColor.DARK_GREEN.toARGB()).textColor(RGBAColor.WHITE.toARGB()),
				BoxStyle.DEFAULT,
				true
			)
		)
	}
}
