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

import java.util.function.BiConsumer;

import speiger.src.collections.floats.lists.FloatArrayList;
import speiger.src.collections.floats.lists.FloatList;
import speiger.src.coreengine.rendering.tesselationOld.IVertexBuilder;
import speiger.src.coreengine.rendering.tesselationOld.Tesselator;

public class DelayedRenderBuffer implements IVertexBuilder
{
	protected FloatList buffer = new FloatArrayList();
	
	@Override
	public DelayedRenderBuffer pos(float x, float y)
	{
		buffer.add(x);
		buffer.add(y);
		return this;
	}
	
	@Override
	public DelayedRenderBuffer pos(float x, float y, float z)
	{
		buffer.add(x);
		buffer.add(y);
		buffer.add(z);
		return this;
	}		
	
	@Override
	public DelayedRenderBuffer color4f(float r, float g, float b, float a)
	{
		buffer.add(r);
		buffer.add(g);
		buffer.add(b);
		buffer.add(a);
		return this;
	}
		
	@Override
	public DelayedRenderBuffer tex(float u, float v)
	{
		buffer.add(u);
		buffer.add(v);
		return this;
	}
	
	@Override
	public IVertexBuilder color3f(float r, float g, float b)
	{
		buffer.add(r);
		buffer.add(g);
		buffer.add(b);
		return this;
	}

	@Override
	public IVertexBuilder normal(float x, float y, float z)
	{
		buffer.add(x);
		buffer.add(y);
		buffer.add(z);
		return this;
	}

	@Override
	public IVertexBuilder custom(float x)
	{
		buffer.add(x);
		return this;
	}

	@Override
	public IVertexBuilder custom(float x, float y)
	{
		buffer.add(x);
		buffer.add(y);
		return this;
	}

	@Override
	public IVertexBuilder custom(float x, float y, float z)
	{
		buffer.add(x);
		buffer.add(y);
		buffer.add(z);
		return this;
	}

	@Override
	public IVertexBuilder custom(float x, float y, float z, float w)
	{
		buffer.add(x);
		buffer.add(y);
		buffer.add(z);
		buffer.add(w);
		return this;
	}

	@Override
	public IVertexBuilder endVertex()
	{
		return this;
	}
	
	public void merge(Tesselator builder, BiConsumer<FloatList, Tesselator> merge)
	{
		merge.accept(buffer, builder);
		buffer.clear();
	}
	
	protected void defaultMerge(FloatList buffer, Tesselator builder)
	{
		if(builder.hasTexture())
		{
			for(int i = 0;i<buffer.size();i+=9)
			{
				builder.pos(buffer.getFloat(i), buffer.getFloat(i + 1), buffer.getFloat(i + 2)).tex(buffer.getFloat(i + 3), buffer.getFloat(i + 4)).color4f(buffer.getFloat(i + 5), buffer.getFloat(i + 6), buffer.getFloat(i + 7), buffer.getFloat(i + 8)).endVertex();
			}
		}
		else
		{
			for(int i = 0;i<buffer.size();i+=7)
			{
				builder.pos(buffer.getFloat(i), buffer.getFloat(i + 1), buffer.getFloat(i + 2)).color4f(buffer.getFloat(i + 3), buffer.getFloat(i + 4), buffer.getFloat(i + 5), buffer.getFloat(i + 6)).endVertex();
			}
		}		
	}
	
	public void merge(Tesselator builder)
	{
		merge(builder, this::defaultMerge);
	}
	
	public boolean hasData()
	{
		return buffer.size() > 0;
	}
}
