package ru.dbotthepony.mc.otm.item.exopack

import com.mojang.serialization.codecs.RecordCodecBuilder
import net.minecraft.ChatFormatting
import net.minecraft.network.chat.Component
import net.minecraft.util.valueproviders.ConstantInt
import net.minecraft.util.valueproviders.IntProvider
import net.minecraft.world.item.ItemStack
import net.minecraft.world.item.Rarity
import net.minecraft.world.item.TooltipFlag
import net.minecraft.world.level.Level
import net.minecraft.world.level.storage.loot.LootContext
import net.minecraft.world.level.storage.loot.functions.LootItemFunction
import net.minecraft.world.level.storage.loot.functions.LootItemFunctionType
import ru.dbotthepony.mc.otm.core.TranslatableComponent
import ru.dbotthepony.mc.otm.core.nbt.set
import ru.dbotthepony.mc.otm.core.tagNotNull
import ru.dbotthepony.mc.otm.data.Codec2Serializer
import ru.dbotthepony.mc.otm.registry.MItemFunctionTypes
import java.util.*

class ProceduralExoPackSlotUpgradeItem : AbstractExoPackSlotUpgradeItem(defaultProperties()) {
	class Randomizer(val slots: IntProvider, val luckBias: IntProvider = ConstantInt.ZERO) : LootItemFunction, LootItemFunction.Builder {
		override fun apply(t: ItemStack, u: LootContext): ItemStack {
			t.tagNotNull[SLOT_COUNT_KEY] = slots.sample(u.random) + (luckBias.sample(u.random) * u.luck / 1024f).coerceAtLeast(0f).toInt()
			return t
		}

		override fun getType(): LootItemFunctionType {
			return MItemFunctionTypes.PROCEDURAL_EXOPACK_UPGRADE
		}

		override fun build(): LootItemFunction {
			return this
		}

		companion object {
			val SERIALIZER = Codec2Serializer<Randomizer>(
				RecordCodecBuilder.create {
					it.group(
						IntProvider.CODEC.fieldOf("slots").forGetter(Randomizer::slots),
						IntProvider.CODEC.optionalFieldOf("luck_bias", ConstantInt.ZERO).forGetter(Randomizer::luckBias),
					).apply(it, ::Randomizer)
				}
			)
		}
	}

	override fun hasDescription(itemStack: ItemStack): Boolean {
		return false
	}

	override fun slotCount(itemStack: ItemStack): Int {
		return itemStack.tag?.getInt(SLOT_COUNT_KEY) ?: 0
	}

	override fun uuid(itemStack: ItemStack): UUID? {
		return null
	}

	override fun appendHoverText(
		p_41421_: ItemStack,
		p_41422_: Level?,
		tooltip: MutableList<Component>,
		p_41424_: TooltipFlag
	) {
		super.appendHoverText(p_41421_, p_41422_, tooltip, p_41424_)

		if (p_41421_.tag?.get(SLOT_COUNT_KEY) == null) {
			tooltip.add(TranslatableComponent("$descriptionId.description").withStyle(ChatFormatting.GRAY))
		}
	}

	companion object {
		const val SLOT_COUNT_KEY = "slotCount"
		const val UUID_KEY = "uuid"
	}
}
