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.Null";
	
	private static final String DEFAULT_RENDERER_TYPE = "org.seasar.jsf.Null";

	private String var_;
	
	private String varIndex_;
	
	private List itemList_;
	
	private int index_;

	public ForEach() {
		setRendererType(DEFAULT_RENDERER_TYPE);
	}

	public String getVar() {
		return var_;
	}
	
	public void setVar(String var) {
		var_ = var;
	}
	
	public String getVarIndex() {
		return varIndex_;
	}
	
	public void setVarIndex(String varIndex) {
		varIndex_ = varIndex;
	}
	
	public int getIndex() {
		return index_;
	}
	
	public Object getCurrent() {
		return itemList_.get(index_);
	}
	
	public int getCount() {
		return itemList_.size();
	}
	
	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 ( ; index_ < itemList_.size(); ++index_) {
			Map requestMap = context.getExternalContext().getRequestMap();
			if (var_ != null) {
				requestMap.put(var_, getCurrent());
			}
			if (varIndex_ != null) {
				requestMap.put(varIndex_, new Integer(index_));
			}
			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];
	}
}