package ru.dbotthepony.mc.otm.triggers

import com.google.gson.JsonObject
import com.google.gson.JsonParseException
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.core.set

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

	override fun getId(): ResourceLocation {
		return ID
	}

	override fun createInstance(pJson: JsonObject, pPlayer: ContextAwarePredicate, pContext: DeserializationContext): Instance {
		return Instance((pJson["distance_to_travel"] as? JsonPrimitive)?.asDouble ?: throw JsonParseException("Invalid 'distance_to_travel' value"))
	}

	fun trigger(player: ServerPlayer, travelled: Double) {
		trigger(player) {
			it.distanceToTravel <= travelled
		}
	}

	class Instance(val distanceToTravel: Double) : AbstractCriterionTriggerInstance(ID, ContextAwarePredicate.ANY) {
		override fun serializeToJson(pConditions: SerializationContext): JsonObject {
			return super.serializeToJson(pConditions).also {
				it["distance_to_travel"] = JsonPrimitive(distanceToTravel)
			}
		}
	}
}
