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

import java.util.Collections;
import java.util.Iterator;
import java.util.List;

import speiger.src.collections.objects.lists.ObjectArrayList;
import speiger.src.coreengine.rendering.guiOld.GuiBase;
import speiger.src.coreengine.rendering.guiOld.GuiComponent;
import speiger.src.coreengine.rendering.guiOld.components.list.BaseListEntry;

public abstract class BaseTreeEntry extends BaseListEntry implements ITreeEntry
{
	protected List<ITreeEntry> children = null;
	protected ITreeEntry parent = null;
	protected int debth;
	protected boolean init = false;
	
	@Override
	public Iterator<ITreeEntry> iterator()
	{
		return isLeaf() ? Collections.emptyIterator() : children.iterator();
	}
	
	@Override
	public boolean isInit()
	{
		return init;
	}
	
	@Override
	public void init(GuiComponent comp, GuiBase owner)
	{
		super.init(comp, owner);
		init = true;
	}
	
	@Override
	public boolean isLeaf()
	{
		return children == null;
	}
	
	@Override
	public void addChild(ITreeEntry child)
	{
		if(isLeaf())
		{
			children = new ObjectArrayList<ITreeEntry>();
		}
		children.add(child);
		child.setParent(this);
		calculateDebth();
		onChange();
	}
	
	@Override
	public void removeChild(ITreeEntry child)
	{
		if(isLeaf())
		{
			return;
		}
		if(children.remove(child))
		{
			child.setParent(null);
			if(children.isEmpty())
			{
				children = null;
			}
			onChange();
		}
	}
	
	protected void onChange()
	{
		
	}
	
	@Override
	public void onClosed()
	{
		super.onClosed();
		if(!isLeaf())
		{
			for(int i = 0;i<children.size();i++)
			{
				children.get(i).onClosed();
			}
		}
	}
	
	@Override
	public int getChildCount()
	{
		return isLeaf() ? 0 : children.size();
	}
	
	@Override
	public ITreeEntry getChild(int index)
	{
		return isLeaf() ? null : children.get(index);
	}
	
	@Override
	public int indexOf(ITreeEntry child)
	{
		return isLeaf() ? -1 : children.indexOf(child);
	}
	
	@Override
	public ITreeEntry getParent()
	{
		return parent;
	}
	
	@Override
	public void setParent(ITreeEntry parent)
	{
		this.parent = parent;
		debth = parent == null ? 0 : parent.getDebth() + 1;
	}
	
	@Override
	public int getDebth()
	{
		return debth;
	}
	
	@Override
	public void calculateDebth()
	{
		debth = parent == null ? 0 : parent.getDebth() + 1;
		if(!isLeaf())
		{
			for(int i = 0,m=children.size();i<m;i++)
			{
				children.get(i).calculateDebth();
			}
		}
	}
}
