/**
 * License Agreement.
 *
 *  JBoss RichFaces - Ajax4jsf Component Library
 *
 * Copyright (C) 2007  Exadel, Inc.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License version 2.1 as published by the Free Software Foundation.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
 */

package org.richfaces.component;

import java.util.Iterator;

import javax.faces.component.UIComponent;
import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;


/**
 * Created 08.03.2008
 * @author Nick Belaevski
 * @since 3.2
 */

public class DataScrollerViewPhaseListener implements PhaseListener {

	/**
	 * 
	 */
	private static final long serialVersionUID = -3614288642745891577L;

	public void afterPhase(PhaseEvent event) {
	}

	private void updateScrollers(UIComponent component) {
	    if (component.isRendered()) {
		if (component instanceof UIDatascroller) {
		    UIDatascroller datascroller = (UIDatascroller) component;
		    datascroller.setupFirstRowValue();
		}

		Iterator<UIComponent> children = component.getFacetsAndChildren();
		while(children.hasNext()) {
		    updateScrollers(children.next());
		}
	    }
	}

	public void beforePhase(PhaseEvent event) {
		FacesContext facesContext = event.getFacesContext();
		UIViewRoot viewRoot = facesContext.getViewRoot();
		if (viewRoot != null) {
			updateScrollers(viewRoot);
		}
	}

	public PhaseId getPhaseId() {
		return PhaseId.RENDER_RESPONSE;
	}

}
