package net.minecraft.resources;

import com.mojang.datafixers.util.Pair;
import com.mojang.serialization.DataResult;
import com.mojang.serialization.DynamicOps;
import com.mojang.serialization.Lifecycle;
import com.mojang.serialization.MapCodec;
import net.minecraft.core.Registry;
import net.minecraft.core.MappedRegistry;
import com.mojang.serialization.Codec;

public final class RegistryDataPackCodec<E> implements Codec<MappedRegistry<E>> {
    private final Codec<MappedRegistry<E>> directCodec;
    private final ResourceKey<Registry<E>> registryKey;
    private final MapCodec<E> elementCodec;
    
    public static <E> RegistryDataPackCodec<E> create(final ResourceKey<Registry<E>> ug, final Lifecycle lifecycle, final MapCodec<E> mapCodec) {
        return new RegistryDataPackCodec<E>(ug, lifecycle, mapCodec);
    }
    
    private RegistryDataPackCodec(final ResourceKey<Registry<E>> ug, final Lifecycle lifecycle, final MapCodec<E> mapCodec) {
        this.directCodec = MappedRegistry.<E>directCodec(ug, lifecycle, mapCodec);
        this.registryKey = ug;
        this.elementCodec = mapCodec;
    }
    
    public <T> DataResult<T> encode(final MappedRegistry<E> gh, final DynamicOps<T> dynamicOps, final T object) {
        return (DataResult<T>)this.directCodec.encode(gh, (DynamicOps)dynamicOps, object);
    }
    
    public <T> DataResult<Pair<MappedRegistry<E>, T>> decode(final DynamicOps<T> dynamicOps, final T object) {
        final DataResult<Pair<MappedRegistry<E>, T>> dataResult4 = (DataResult<Pair<MappedRegistry<E>, T>>)this.directCodec.decode((DynamicOps)dynamicOps, object);
        if (dynamicOps instanceof RegistryReadOps) {
            return (DataResult<Pair<MappedRegistry<E>, T>>)dataResult4.flatMap(pair -> ((RegistryReadOps)dynamicOps).<E>decodeElements((MappedRegistry<E>)pair.getFirst(), this.registryKey, this.elementCodec).map(gh -> Pair.of(gh, pair.getSecond())));
        }
        return dataResult4;
    }
    
    @Override
    public String toString() {
        return "RegistryDapaPackCodec[" + this.directCodec + " " + this.registryKey + " " + this.elementCodec + "]";
    }
}
