package org.richfaces.component;

import java.util.Iterator;
import java.util.NoSuchElementException;

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

/**
 * Iterator for all children table columns.
 * @author asmirnov
 *
 */
class ColumnsIterator implements Iterator<UIComponent>{
	

	private UIComponent next;
	
	private boolean initialized = false;
	
	protected Iterator<UIComponent> childrenIterator;
	
	public ColumnsIterator(UIComponent dataTable) {
		this.childrenIterator = dataTable.getChildren().iterator();
	}

	public boolean hasNext() {
		if(!initialized){
			next = nextColumn();
			initialized = true;
		}
		return null != next;
	}

	public UIComponent next() {
		if (!hasNext()) {
			throw new NoSuchElementException();
		}
		UIComponent result = next;
		next = nextColumn();
		return result;
	}

	public void remove() {
		throw new UnsupportedOperationException("Iterator is read-only");			
	}
	
	protected UIComponent nextColumn(){
		UIComponent nextColumn = null;
		while (childrenIterator.hasNext()) {
			UIComponent child = childrenIterator.next();
			if(child instanceof UIColumn || child instanceof Column){
				nextColumn = child;
				break;
			}
		}
		return nextColumn;
	}
	
}