package ru.dbotthepony.mc.otm.triggers

import com.google.gson.JsonObject
import com.google.gson.JsonPrimitive
import net.minecraft.advancements.critereon.*
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 ru.dbotthepony.mc.otm.core.nbt.set
import ru.dbotthepony.mc.otm.core.set
import java.util.function.Predicate

object AndroidResearchTrigger : SimpleCriterionTrigger<AndroidResearchTrigger.Instance>() {
	val ID = ResourceLocation(OverdriveThatMatters.MOD_ID, "android_research")

	override fun getId(): ResourceLocation {
		return ID
	}

	override fun createInstance(
		p_66248_: JsonObject,
		p_286603_: ContextAwarePredicate,
		p_66250_: DeserializationContext
	): Instance {
		return Instance(
			p_66248_["research"]?.asString?.let(::ResourceLocation)
		)
	}

	fun trigger(player: ServerPlayer, research: AndroidResearchType) {
		trigger(player) {
			it.test(research)
		}
	}

	class Instance(val research: ResourceLocation?) : AbstractCriterionTriggerInstance(ID, ContextAwarePredicate.ANY), Predicate<AndroidResearchType> {
		constructor(research: AndroidResearchType) : this(research.id)

		override fun test(t: AndroidResearchType): Boolean {
			return research == null || t.id == research
		}

		override fun serializeToJson(p_16979_: SerializationContext): JsonObject {
			return super.serializeToJson(p_16979_).also {
				if (research != null)
					it["research"] = JsonPrimitive(research.toString())
			}
		}
	}
}
