package ru.dbotthepony.mc.otm.data.condition

import com.mojang.serialization.Codec
import com.mojang.serialization.codecs.RecordCodecBuilder
import net.minecraft.world.level.storage.loot.LootContext
import net.minecraft.world.level.storage.loot.predicates.LootItemCondition
import net.minecraft.world.level.storage.loot.predicates.LootItemConditionType
import ru.dbotthepony.mc.otm.data.Codec2Serializer
import ru.dbotthepony.mc.otm.registry.MLootItemConditions

/**
 * u serious?
 */
data class ChanceCondition(val chance: Double) : LootItemCondition, LootItemCondition.Builder {
	init {
		require(chance in 0.0 .. 1.0) { "Invalid chance: $chance" }
	}

	override fun test(t: LootContext): Boolean {
		return t.random.nextDouble() < chance
	}

	override fun getType(): LootItemConditionType {
		return MLootItemConditions.CHANCE
	}

	override fun build(): LootItemCondition {
		return this
	}

	companion object {
		val SERIALIZER = Codec2Serializer<ChanceCondition>(RecordCodecBuilder.create { it.group(Codec.doubleRange(0.0, 1.0).fieldOf("chance").forGetter(ChanceCondition::chance)).apply(it, ::ChanceCondition) })
	}
}
