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.Logic";
	
	public static final String DEFAULT_RENDERER_TYPE = null;

	private String var;
	
	private String varIndex;

	public ForEach() {
		setRendererType(DEFAULT_RENDERER_TYPE);
	}

	public String getVar() {
		return var;
	}
	
	public void setVar(String var) {
		this.var = var;
	}
	
	public String getVarIndex() {
		return varIndex;
	}
	
	public void setVarIndex(String varIndex) {
		this.varIndex = varIndex;
	}
	
	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;
		}
	}
	
	/**
	 * @see javax.faces.component.UIComponent#encodeChildren(javax.faces.context.FacesContext)
	 */
	public void encodeChildren(FacesContext context) throws IOException {
		if (!isRendered()) {
			return;
		}
		List itemList = getItemList();
		if (itemList == null || itemList.isEmpty()) {
			return;
		}
		for (int i = 0; i < itemList.size(); ++i) {
			Map requestMap = context.getExternalContext().getRequestMap();
			if (var != null) {
				requestMap.put(var, itemList.get(i));
			}
			if (varIndex != null) {
				requestMap.put(varIndex, new Integer(i));
			}
			RenderUtil.encodeChildren(context, this);
		}
	}

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

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