package ru.dbotthepony.mc.otm.triggers

import com.mojang.serialization.Codec
import com.mojang.serialization.codecs.RecordCodecBuilder
import net.minecraft.advancements.critereon.ContextAwarePredicate
import net.minecraft.resources.ResourceLocation
import net.minecraft.server.level.ServerPlayer
import ru.dbotthepony.mc.otm.OverdriveThatMatters
import ru.dbotthepony.mc.otm.core.ResourceLocation
import java.util.*

val ExopackObtainedTrigger = SingletonTrigger(ResourceLocation(OverdriveThatMatters.MOD_ID, "exopack_obtained"))
val ExopackGainedCraftingTrigger = SingletonTrigger(ResourceLocation(OverdriveThatMatters.MOD_ID, "exopack_gained_crafting"))
val ExopackGainedSmeltingTrigger = SingletonTrigger(ResourceLocation(OverdriveThatMatters.MOD_ID, "exopack_gained_smelting"))
val ExopackGainedEnderAccessTrigger = SingletonTrigger(ResourceLocation(OverdriveThatMatters.MOD_ID, "exopack_gained_ender_access"))

val ExopackBatterySlotTrigger = ItemTrigger(ResourceLocation(OverdriveThatMatters.MOD_ID, "exopack_battery_slot"))

object ExopackSlotsExpandedTrigger : MCriterionTrigger<ExopackSlotsExpandedTrigger.Instance>(ResourceLocation(OverdriveThatMatters.MOD_ID, "exopack_expanded")) {
	override val codec: Codec<Instance> = RecordCodecBuilder.create {
		it.group(
			Codec.intRange(0, Int.MAX_VALUE).optionalFieldOf("minGained", 0).forGetter(Instance::minGained),
			Codec.intRange(0, Int.MAX_VALUE).optionalFieldOf("minTotal", 0).forGetter(Instance::minTotal),
			ContextAwarePredicate.CODEC.optionalFieldOf("player").forGetter(Instance::playerPredicate)
		).apply(it, ::Instance)
	}

	fun trigger(player: ServerPlayer, gained: Int, total: Int) {
		trigger(player) { it.minGained <= gained && it.minTotal <= total }
	}

	class Instance(val minGained: Int = 0, val minTotal: Int = 0, player: Optional<ContextAwarePredicate> = Optional.empty()) : AbstractInstance(player) {
		init {
			require(minGained >= 0) { "Invalid minGained $minGained" }
			require(minTotal >= 0) { "Invalid minTotal $minTotal" }
		}
	}
}
