package ru.dbotthepony.mc.otm.matter

import com.mojang.datafixers.util.Either
import com.mojang.serialization.Codec
import com.mojang.serialization.codecs.RecordCodecBuilder
import net.minecraft.resources.ResourceLocation
import net.minecraft.tags.TagKey
import net.minecraft.world.item.Item

open class DeleteAction(
	id: Either<ResourceLocation, TagKey<Item>>,
	errorOnFailure: Boolean = false,
) : AbstractRegistryAction(id, errorOnFailure) {
	override fun doUpdate(registry: MutableCollection<IMutableRegistryEntry>, source: ResourceLocation) {
		val iterator = registry.iterator()

		for (value in iterator) {
			if (value.name == id) {
				iterator.remove()
				return
			}
		}

		fail { "Could not find matter value with name $id (source: $source)" }
	}

	override val type: Type<*>
		get() = Companion

	companion object : Type<DeleteAction> {
		override val codec: Codec<DeleteAction> by lazy {
			RecordCodecBuilder.create {
				it.group(
					TargetCodec.fieldOf("id").forGetter(DeleteAction::id),
					Codec.BOOL.optionalFieldOf("errorOnFailure", false).forGetter(DeleteAction::errorOnFailure)
				).apply(it, ::DeleteAction)
			}
		}
	}
}

class BlacklistAction(id: Either<ResourceLocation, TagKey<Item>>) : DeleteAction(id) {
	override val type: Type<*>
		get() = Companion

	companion object : Type<BlacklistAction> {
		override val codec: Codec<BlacklistAction> by lazy {
			RecordCodecBuilder.create {
				it.group(
					TargetCodec.fieldOf("id").forGetter(BlacklistAction::id)
				).apply(it, ::BlacklistAction)
			}
		}
	}
}
