package net.minecraft.resources;

import java.util.Optional;
import com.mojang.datafixers.util.Pair;
import net.minecraft.util.Codecs;
import net.minecraft.core.WritableRegistry;
import com.mojang.serialization.DataResult;
import com.mojang.serialization.MapCodec;
import net.minecraft.core.Registry;
import com.mojang.serialization.DynamicOps;
import net.minecraft.core.RegistryAccess;

public class RegistryWriteOps<T> extends DelegatingOps<T> {
    private final RegistryAccess registryHolder;
    
    public static <T> RegistryWriteOps<T> create(final DynamicOps<T> dynamicOps, final RegistryAccess gm) {
        return new RegistryWriteOps<T>(dynamicOps, gm);
    }
    
    private RegistryWriteOps(final DynamicOps<T> dynamicOps, final RegistryAccess gm) {
        super(dynamicOps);
        this.registryHolder = gm;
    }
    
    protected <E> DataResult<T> encode(final E object1, final T object2, final ResourceKey<Registry<E>> ug, final MapCodec<E> mapCodec) {
        final Optional<WritableRegistry<E>> optional6 = this.registryHolder.<E>registry(ug);
        if (optional6.isPresent()) {
            final WritableRegistry<E> gs7 = optional6.get();
            final Optional<ResourceKey<E>> optional7 = gs7.getResourceKey(object1);
            if (optional7.isPresent()) {
                final ResourceKey<E> ug2 = optional7.get();
                if (gs7.persistent(ug2)) {
                    return (DataResult<T>)Codecs.<E>withName(ug, mapCodec).codec().encode(Pair.of((Object)ug2, (Object)object1), (DynamicOps)this.delegate, object2);
                }
                return (DataResult<T>)ResourceLocation.CODEC.encode(ug2.location(), (DynamicOps)this.delegate, object2);
            }
        }
        return (DataResult<T>)mapCodec.codec().encode(object1, (DynamicOps)this.delegate, object2);
    }
}
