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

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

import speiger.src.collections.objects.lists.ObjectArrayList;
import speiger.src.collections.objects.lists.ObjectList;
import speiger.src.collections.objects.utils.ObjectLists;
import speiger.src.coreengine.rendering.guiOld.GuiComponent;

public class CheckBoxGroup<T extends GuiComponent & ICheckBox<T>> implements Consumer<GuiComponent>
{
	ObjectList<T> checkboxes = new ObjectArrayList<T>();
	int selectedIndex = -1;
	Runnable listener;
	
	public CheckBoxGroup<T> setListener(Runnable listener)
	{
		this.listener = listener;
		return this;
	}
	
	public T add(T box)
	{
		checkboxes.add(box);
		if(box.isChecked())
		{
			if(selectedIndex == -1)
			{
				selectedIndex = checkboxes.indexOf(box);
			}
			else
			{
				box.setChecked(false);
			}
		}
		box.onAction(this);
		return box;
	}
	
	public boolean remove(T box)
	{
		boolean result = checkboxes.remove(box);
		if(result)
		{
			if(box.isChecked())
			{
				selectedIndex = -1;	
			}
			box.removeChangeListener(this);
		}
		return result;
	}
	
	public T getSelected()
	{
		return selectedIndex == -1 ? null : checkboxes.get(selectedIndex);
	}
	
	public boolean hasSelected()
	{
		return selectedIndex != -1;
	}
	
	public int getSelectedIndex()
	{
		return selectedIndex;
	}
	
	public List<T> getCheckBoxes()
	{
		return ObjectLists.unmodifiable(checkboxes);
	}
	
	public void setChecked(int selected)
	{
		if(selectedIndex != -1)
		{
			checkboxes.get(selectedIndex).setChecked(false);
		}
		selectedIndex = selected;
		if(selectedIndex != -1)
		{
			checkboxes.get(selectedIndex).setChecked(true);
		}
	}

	@Override
	@SuppressWarnings("unchecked")
	public void accept(GuiComponent t)
	{
		ICheckBox<T> box = t.tryCast(ICheckBox.class);
		if(box == null)
		{
			return;
		}
		int index = checkboxes.indexOf(t);
		if(index == -1)
		{
			return;
		}
		if(box.isChecked())
		{
			if(selectedIndex != -1)
			{
				checkboxes.get(selectedIndex).setChecked(false);
			}
			selectedIndex = index;
		}
		else
		{
			selectedIndex = -1;
		}
		if(listener != null)
		{
			listener.run();
		}
	}
}
