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

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.guiOld.helper.box.IGuiBox;

public class VerticalLayout implements Consumer<GuiComponent>
{
	GuiComponent parent;
	List<GuiComponent> components = new ObjectArrayList<>();
	IGuiBox box;
	float padding;
	boolean changing = false;
	
	public VerticalLayout(List<GuiComponent> components, IGuiBox box, float padding)
	{
		this.components.addAll(components);
		for(int i = 0;i<components.size();i++)
		{
			components.get(i).onChange(this).onClose(this::removeComponent);
		}
		this.box = box;
		this.padding = padding;
	}
	
	public VerticalLayout(IGuiBox box, float padding)
	{
		this.box = box;
		this.padding = padding;
	}
	
	public void setParent(GuiComponent parent)
	{
		this.parent = parent;
	}
	
	public <T extends GuiComponent> T addComponent(T gui)
	{
		components.add(gui);
		gui.onChange(this);
		gui.onClose(this::removeComponent);
		accept(null);
		return gui;
	}
	
	public void removeComponent(GuiComponent gui)
	{
		if(components.remove(gui))
		{
			gui.removeChangeListener(this);
			gui.removeCloseListener(this::removeComponent);
			accept(null);
		}
	}
	
	@Override
	public void accept(GuiComponent t)
	{
		if(changing) return;
		changing = true;
		float minX = box.getBaseX();
		float minY = box.getBaseY();
		float currentY = 0F;
		for(int i = 0;i<components.size();i++)
		{
			GuiComponent component = components.get(i);
			component.setMassChanging();
			float[] bounds = new float[4];
			component.calculateActualBounds(bounds, true);
			float height = (bounds[3] - bounds[1]) + padding;
			component.set(minX, minY + currentY);
			currentY += height;
			component.finishMassChanging(true);
		}
		if(parent != null)
		{
			parent.onChanged(false);
		}
		changing = false;
	}
}
