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

import net.minecraft.nbt.CompoundTag
import net.minecraft.nbt.ListTag
import net.minecraft.resources.ResourceLocation
import ru.dbotthepony.mc.otm.block.entity.MachineItemJob
import ru.dbotthepony.mc.otm.block.entity.MatteryWorkerBlockEntity
import ru.dbotthepony.mc.otm.compat.jade.JadeTagKeys
import ru.dbotthepony.mc.otm.compat.jade.JadeUids
import ru.dbotthepony.mc.otm.core.math.RGBAColor
import ru.dbotthepony.mc.otm.core.nbt.getCompoundList
import ru.dbotthepony.mc.otm.core.nbt.getItemStack
import ru.dbotthepony.mc.otm.core.nbt.set
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 MatteryWorkerProvider : IBlockComponentProvider, IServerDataProvider<BlockAccessor> {
	override fun getUid(): ResourceLocation = JadeUids.MATTERY_WORKER

	override fun appendServerData(data: CompoundTag, accessor: BlockAccessor) {
		if (accessor.blockEntity is MatteryWorkerBlockEntity<*>) {
			val worker = accessor.blockEntity as MatteryWorkerBlockEntity<*>

			val workerData = CompoundTag()

			workerData["jobs"] = ListTag().also {
				for (job in worker.jobEventLoops) {
					val jobData = CompoundTag()
					jobData.putFloat("workProgress", job.workProgress)
					jobData.putBoolean("isIdling", job.isIdling)
					jobData.putBoolean("isUnableToProcess", job.isUnableToProcess)

					if (job.currentJob is MachineItemJob) {
						val currentJob = job.currentJob as MachineItemJob
						jobData.put("itemStack", currentJob.itemStack.serializeNBT())
					}

					it.add(jobData)
				}
			}

			data.put(JadeTagKeys.MATTERY_WORKER_DATA, workerData)
		}
	}

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

		if (!data.contains(JadeTagKeys.MATTERY_WORKER_DATA)) return
		val workerData = data.getCompound(JadeTagKeys.MATTERY_WORKER_DATA)

		val elementHelper = tooltip.elementHelper
		val style = elementHelper.progressStyle().color(RGBAColor.WHITE.toARGB())
		val styleError = elementHelper.progressStyle().color(RGBAColor.REDDISH.toARGB())

		for (job in workerData.getCompoundList("jobs")) {
			val progress = job.getFloat("workProgress")
			val isIdling = job.getBoolean("isIdling")
			val isUnableToProcess = job.getBoolean("isUnableToProcess")
			val itemStack = job.getItemStack("itemStack")

			if (!isIdling) {
				if (!itemStack.isEmpty) {
					tooltip.add(elementHelper.smallItem(itemStack))
					tooltip.append(elementHelper.text(itemStack.hoverName))
				}

				tooltip.add(
					elementHelper.progress(
						progress,
						null,
						if (isUnableToProcess) styleError else style,
						BoxStyle.DEFAULT,
						true
					)
				)
			}
		}
	}
}
