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.android.AndroidResearchType
import java.util.*
import java.util.function.Predicate

object AndroidResearchTrigger : MCriterionTrigger<AndroidResearchTrigger.Instance>(ResourceLocation(OverdriveThatMatters.MOD_ID, "android_research")) {
	fun trigger(player: ServerPlayer, research: AndroidResearchType) {
		trigger(player) { it.test(research) }
	}

	override val codec: Codec<Instance> = RecordCodecBuilder.create {
		it.group(
			ResourceLocation.CODEC.optionalFieldOf("research").forGetter(Instance::research),
			playerPredicateCodec.forGetter(Instance::playerPredicate)
		).apply(it, ::Instance)
	}

	class Instance(val research: Optional<ResourceLocation>, player: Optional<ContextAwarePredicate> = Optional.empty()) : AbstractInstance(player), Predicate<AndroidResearchType> {
		constructor(research: ResourceLocation) : this(Optional.of(research))
		constructor(research: AndroidResearchType) : this(Optional.of(research.id))

		override fun test(t: AndroidResearchType): Boolean {
			return research.map { it == t.id }.orElse(true)
		}
	}
}
