package net.minecraft.client.renderer.block;

import net.minecraft.world.level.block.state.properties.Property;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.client.resources.model.ModelResourceLocation;
import java.util.Iterator;
import net.minecraft.world.level.block.Block;
import net.minecraft.core.Registry;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import com.google.common.collect.Maps;
import net.minecraft.client.resources.model.ModelManager;
import net.minecraft.client.resources.model.BakedModel;
import net.minecraft.world.level.block.state.BlockState;
import java.util.Map;

public class BlockModelShaper {
    private final Map<BlockState, BakedModel> modelByStateCache;
    private final ModelManager modelManager;
    
    public BlockModelShaper(final ModelManager enm) {
        this.modelByStateCache = Maps.newIdentityHashMap();
        this.modelManager = enm;
    }
    
    public TextureAtlasSprite getParticleIcon(final BlockState cfj) {
        return this.getBlockModel(cfj).getParticleIcon();
    }
    
    public BakedModel getBlockModel(final BlockState cfj) {
        BakedModel enh3 = this.modelByStateCache.get(cfj);
        if (enh3 == null) {
            enh3 = this.modelManager.getMissingModel();
        }
        return enh3;
    }
    
    public ModelManager getModelManager() {
        return this.modelManager;
    }
    
    public void rebuildCache() {
        this.modelByStateCache.clear();
        for (final Block bvr3 : Registry.BLOCK) {
            final BakedModel bakedModel;
            bvr3.getStateDefinition().getPossibleStates().forEach(cfj -> bakedModel = this.modelByStateCache.put(cfj, this.modelManager.getModel(stateToModelLocation(cfj))));
        }
    }
    
    public static ModelResourceLocation stateToModelLocation(final BlockState cfj) {
        return stateToModelLocation(Registry.BLOCK.getKey(cfj.getBlock()), cfj);
    }
    
    public static ModelResourceLocation stateToModelLocation(final ResourceLocation uh, final BlockState cfj) {
        return new ModelResourceLocation(uh, statePropertiesToString(cfj.getValues()));
    }
    
    public static String statePropertiesToString(final Map<Property<?>, Comparable<?>> map) {
        final StringBuilder stringBuilder2 = new StringBuilder();
        for (final Map.Entry<Property<?>, Comparable<?>> entry4 : map.entrySet()) {
            if (stringBuilder2.length() != 0) {
                stringBuilder2.append(',');
            }
            final Property<?> cgl5 = entry4.getKey();
            stringBuilder2.append(cgl5.getName());
            stringBuilder2.append('=');
            stringBuilder2.append(BlockModelShaper.getValue(cgl5, entry4.getValue()));
        }
        return stringBuilder2.toString();
    }
    
    private static <T extends Comparable<T>> String getValue(final Property<T> cgl, final Comparable<?> comparable) {
        return cgl.getName((T)comparable);
    }
}
