/**
 * 
 */
package org.richfaces.component;

import java.util.Iterator;

import javax.faces.component.UIColumn;
import javax.faces.component.UIComponent;

class FixedChildrenIterator extends DataIterator {

	private  Iterator<UIComponent> currentColumnIterator;

	
	public FixedChildrenIterator(UIComponent dataTable) {
		super(dataTable);
	}
	
	@Override
	protected UIComponent nextColumn() {
		UIComponent nextColumn = null;
		if(null != currentColumnIterator){
			nextColumn = currentColumnIterator.next();
			checkNextColumnChild();
		} else {
			while (childrenIterator.hasNext()) {
				UIComponent child = childrenIterator.next();
				if ( child instanceof UIColumn || child instanceof Column ) {
					boolean rendered = true;
					try {
						rendered = child.isRendered();
					} catch (Exception e) {
						// This exception can be thrown for a header/footer facets 
						// there column rendered attribute was binded to a row variable.
					}
					if (rendered) {
						Iterator<UIComponent> iterator = getColumnChildrenIterator(child);
						if (iterator.hasNext()) {
							currentColumnIterator = iterator;
							nextColumn = currentColumnIterator.next();
							checkNextColumnChild();
							break;
						}

					}
				} else if (checkAjaxComponent(child)) {
					nextColumn = child;
					break;
				}
			}
		}
		if(null == nextColumn){
			while (facetsIterator.hasNext()) {
				UIComponent child = facetsIterator.next();
				if(checkAjaxComponent(child)){
					nextColumn = child;
					break;
				}
			}
		}
		return nextColumn;
	}

	@Override
	protected boolean checkAjaxComponent(UIComponent child) {
		return !super.checkAjaxComponent(child);
	}
	
	@Override
	protected Iterator<UIComponent> getColumnChildrenIterator(
			UIComponent child) {
		return child.getFacets().values().iterator();
	}
	
		protected void checkNextColumnChild() {
			if(!currentColumnIterator.hasNext()){
				currentColumnIterator = null;
			}
		}

}