package speiger.src.coreengine.rendering.guiOld.components.layouts;

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

import speiger.src.coreengine.math.vector.floats.Vec2f;
import speiger.src.coreengine.rendering.guiOld.GuiComponent;
import speiger.src.coreengine.rendering.guiOld.helper.box.IGuiBox;

public class FlowLayout implements Consumer<GuiComponent>
{
	IGuiBox box;
	List<? extends GuiComponent> components;
	Vec2f padding;
	
	public FlowLayout(IGuiBox box, Vec2f padding, List<? extends GuiComponent> components)
	{
		this.padding = padding;
		this.box = box;
		this.components = components;
	}
	
	@Override
	public void accept(GuiComponent t)
	{
		float minX = box.getRelativeX();
		float minY = box.getRelativeY();
		float maxWidth = box.getWidth();
		int xInserted = 0;
		int yInserted = 0;
		float widthUsed = 0F;
		float heightOffset = 0F;
		float maxHeight = 0F;
		for(int i = 0,m=components.size();i<m;i++)
		{
			GuiComponent component = components.get(i);
			float[] bounds = new float[4];
			component.calculateActualBounds(bounds, true);
			float width = bounds[2] - bounds[0];
			if(widthUsed + width + padding.x() >= maxWidth && xInserted > 0)
			{
				xInserted = 0;
				maxHeight += heightOffset;
				heightOffset = 0F;
				widthUsed = 0F;
				yInserted++;
			}
			component.set(minX + widthUsed + padding.x(), minY + maxHeight + (padding.y() * yInserted));
			heightOffset = Math.max(heightOffset, bounds[3] - bounds[1]);
			widthUsed += width + padding.x();
			xInserted++;
		}
	}
	
}
