package speiger.src.coreengine.rendering.guiOld.renderer.buffer;

import java.util.Iterator;
import java.util.List;
import java.util.function.Consumer;

import speiger.src.collections.objects.lists.ObjectArrayList;
import speiger.src.coreengine.rendering.guiOld.GuiComponent;
import speiger.src.coreengine.rendering.models.DrawCall;
import speiger.src.coreengine.rendering.tesselation.format.VertexFormat;
import speiger.src.coreengine.rendering.tesselationOld.Tesselator;
import speiger.src.coreengine.utils.collections.iterators.IndexIterator;
import speiger.src.coreengine.utils.collections.iterators.IterableWrapper;

public class RenderBuffer implements Consumer<GuiComponent>, Iterable<DrawCall>
{
	List<DrawCall> drawCalls = new ObjectArrayList<>();
	Tesselator tesselator;
	
	public RenderBuffer(Tesselator tesselator)
	{
		this.tesselator = tesselator;
	}
	
	@Override
	public void accept(GuiComponent t)
	{
		clear();
	}
	
	public DrawCall get(int index)
	{
		return drawCalls.get(index);
	}
	
	public void addDrawCall(DrawCall call)
	{
		drawCalls.add(call);
	}
	
	public void clear()
	{
		drawCalls.clear();
	}
	
	public Tesselator start(int shape, VertexFormat format)
	{
		return tesselator.begin(shape, format);
	}
	
	public void finishShape(int texture, Tesselator tesselator)
	{
		if(!tesselator.isDrawing())
		{
			throw new IllegalStateException("Tesselator wasnt filled");
		}
		tesselator.finishData();
		if(tesselator.getVertexCount() <= 0)
		{
			return;
		}
		drawCalls.add(tesselator.getDrawCall(texture));
	}
	
	public void finishShape(int texture)
	{
		finishShape(texture, tesselator);
	}
	
	@Override
	public Iterator<DrawCall> iterator()
	{
		return drawCalls.iterator();
	}
	
	public Iterable<DrawCall> selectionIterator(int...indexes)
	{
		return IterableWrapper.wrap(new IndexIterator<>(drawCalls, indexes));
	}
}
