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.advancements.critereon.ItemPredicate
import net.minecraft.resources.ResourceLocation
import net.minecraft.server.level.ServerPlayer
import net.minecraft.world.item.ItemStack
import java.util.*

class ItemTrigger(id: ResourceLocation) : MCriterionTrigger<ItemTrigger.Instance>(id) {
	fun trigger(player: ServerPlayer, item: ItemStack) {
		trigger(player) { if (it.invert) !it.predicate.test(item) else it.predicate.test(item) }
	}

	override val codec: Codec<Instance> = RecordCodecBuilder.create {
		it.group(
			ItemPredicate.CODEC.fieldOf("predicate").forGetter(Instance::predicate),
			Codec.BOOL.optionalFieldOf("invert", false).forGetter(Instance::invert),
			ContextAwarePredicate.CODEC.optionalFieldOf("player").forGetter(Instance::playerPredicate)
		).apply(it, ::Instance)
	}

	inner class Instance(val predicate: ItemPredicate, val invert: Boolean = false, player: Optional<ContextAwarePredicate> = Optional.empty()) : AbstractInstance(player)
}
