package net.silentchaos512.lib.client.model;

import com.google.common.collect.ImmutableList;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.renderer.block.model.BakedQuad;
import net.minecraft.client.renderer.vertex.VertexFormat;
import net.minecraft.util.EnumFacing;
import net.minecraftforge.client.model.IModel;

import java.util.List;

public abstract class LayeredBakedModel implements ILayeredBakedModel {
    protected final IModel parent;
    protected final ImmutableList<ImmutableList<BakedQuad>> quads;
    protected final VertexFormat format;

    public LayeredBakedModel(IModel parent, ImmutableList<ImmutableList<BakedQuad>> immutableList, VertexFormat format) {
        this.quads = immutableList;
        this.format = format;
        this.parent = parent;
    }

    @Override
    public List<BakedQuad> getQuads(IBlockState state, EnumFacing side, long indexNotRand) {
        if (side != null) return ImmutableList.of();

        int index = (int) indexNotRand;
        List<BakedQuad> list = this.quads.get(index);
        if (list == null) return ImmutableList.of();

        return list;
    }

    @Override
    public boolean isBuiltInRenderer() {
        return true;
    }

    @Override
    public int getLayerCount() {
        return this.quads.size();
    }

    public IModel getParent() {
        return this.parent;
    }

    public VertexFormat getVertexFormat() {
        return this.format;
    }
}

@@ -333,24 +333,58 @@
 el.IModel;%0A%0A
+import javax.annotation.Nullable;%0A
 import java.
@@ -609,16 +609,68 @@
  format;
+%0A    private ImmutableList%3CBakedQuad%3E allQuadsCache;
 %0A%0A    pu
@@ -938,16 +938,26 @@
 etQuads(
+@Nullable 
 IBlockSt
@@ -966,16 +966,26 @@
 e state,
+ @Nullable
  EnumFac
@@ -1036,17 +1036,17 @@
 ide 
-!
+=
 = null) 
 retu
@@ -1045,36 +1045,14 @@
 ll) 
-return ImmutableList.of();%0A%0A
+%7B%0A    
     
@@ -1099,127 +1099,730 @@
     
-List%3CBakedQuad%3E list = this.quads.get(index);%0A        if (list == null) return ImmutableList.of();%0A%0A        return list
+    // Check invalid index%0A            if (index %3C 0) %7B%0A                // Return everything in one? Better than nothing.%0A                if (allQuadsCache == null) %7B%0A                    ImmutableList.Builder%3CBakedQuad%3E builder = ImmutableList.builder();%0A                    for (List%3CBakedQuad%3E list : quads) %7B%0A                        for (BakedQuad quad : list) %7B%0A                            builder.add(quad);%0A                        %7D%0A                    %7D%0A%0A                    allQuadsCache = builder.build();%0A                %7D%0A%0A                return allQuadsCache;%0A            %7D else if (index %3C quads.size()) %7B%0A                return this.quads.get(index);%0A            %7D%0A        %7D%0A        return ImmutableList.of()
 ;%0A  

Handle invalid index on SGear models (SilentChaos512/SilentGems#348)