package org.seasar.jsf.component;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.faces.component.UIComponentBase;
import javax.faces.context.FacesContext;

import org.seasar.jsf.JsfConstants;
import org.seasar.jsf.util.BindingUtil;
import org.seasar.jsf.util.RenderUtil;

/**
 * @author higa
 *  
 */
public class ForEach extends UIComponentBase {

	public static final String COMPONENT_TYPE = "org.seasar.jsf.ForEach";

	public static final String COMPONENT_FAMILY = "org.seasar.jsf.ForEach";

	private String var_;
	
	private List itemList_;

	public ForEach() {
	}

	public String getVar() {
		return var_;
	}
	
	public void setVar(String var) {
		var_ = var;
	}
	
	protected List getItemList() {
		Object items = BindingUtil.getBindingValue(this, JsfConstants.ITEMS_ATTR);
		if (items == null) {
			return null;
		} else if (items instanceof List) {
			return (List) items;
		} else if (items.getClass().isArray()) {
			return Arrays.asList((Object[]) items);
		} else {
			throw new IllegalStateException(JsfConstants.ITEMS_ATTR);
		}
	}

	/**
	 * @see javax.faces.component.UIComponent#getFamily()
	 */
	public String getFamily() {
		return COMPONENT_FAMILY;
	}
	
	public boolean getRendersChildren() {
		return true;
	}

	public void encodeBegin(FacesContext context) throws IOException {
		if (context == null) {
			throw new NullPointerException("context");
		}
		if (!isRendered()) {
			return;
		}
		itemList_ = getItemList();
	}
	
	/**
	 * @see javax.faces.component.UIComponent#encodeChildren(javax.faces.context.FacesContext)
	 */
	public void encodeChildren(FacesContext context) throws IOException {
		if (itemList_ == null || itemList_.isEmpty()) {
			return;
		}
		for (int i = 0; i < itemList_.size(); ++i) {
			Map requestMap = context.getExternalContext().getRequestMap();
			requestMap.put(var_, itemList_.get(i));
			RenderUtil.encodeChildren(context, this);
		}
	}

	public void encodeEnd(FacesContext context) throws IOException {
		itemList_ = null;
	}
	
	public Object saveState(FacesContext context) {
		Object[] values = new Object[2];
		values[0] = super.saveState(context);
		values[1] = var_;
		return values;
	}

	public void restoreState(FacesContext context, Object state) {
		Object values[] = (Object[]) state;
		super.restoreState(context, values[0]);
		var_ = (String) values[1];
	}
}