package net.minecraft.resources;

import com.mojang.datafixers.util.Pair;
import com.mojang.serialization.DataResult;
import com.mojang.serialization.DynamicOps;
import com.mojang.serialization.MapCodec;
import net.minecraft.core.Registry;
import java.util.function.Supplier;
import com.mojang.serialization.Codec;

public final class RegistryFileCodec<E> implements Codec<Supplier<E>> {
    private final ResourceKey<Registry<E>> registryKey;
    private final MapCodec<E> elementCodec;
    
    public static <E> RegistryFileCodec<E> create(final ResourceKey<Registry<E>> ug, final MapCodec<E> mapCodec) {
        return new RegistryFileCodec<E>(ug, mapCodec);
    }
    
    private RegistryFileCodec(final ResourceKey<Registry<E>> ug, final MapCodec<E> mapCodec) {
        this.registryKey = ug;
        this.elementCodec = mapCodec;
    }
    
    public <T> DataResult<T> encode(final Supplier<E> supplier, final DynamicOps<T> dynamicOps, final T object) {
        if (dynamicOps instanceof RegistryWriteOps) {
            return ((RegistryWriteOps)dynamicOps).<E>encode(supplier.get(), object, this.registryKey, this.elementCodec);
        }
        return (DataResult<T>)this.elementCodec.codec().encode(supplier.get(), (DynamicOps)dynamicOps, object);
    }
    
    public <T> DataResult<Pair<Supplier<E>, T>> decode(final DynamicOps<T> dynamicOps, final T object) {
        if (dynamicOps instanceof RegistryReadOps) {
            return ((RegistryReadOps)dynamicOps).<E>decodeElement(object, this.registryKey, this.elementCodec);
        }
        return (DataResult<Pair<Supplier<E>, T>>)this.elementCodec.codec().decode((DynamicOps)dynamicOps, object).map(pair -> pair.mapFirst(object -> () -> object));
    }
    
    @Override
    public String toString() {
        return "RegistryFileCodec[" + this.registryKey + " " + this.elementCodec + "]";
    }
}
