/**
 * 
 */
package org.richfaces.renderkit;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
import javax.faces.model.SelectItem;

import org.ajax4jsf.util.InputUtils;
import org.ajax4jsf.util.SelectUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.richfaces.component.UIInplaceSelect;

/**
 * InplaceSelect base renderer implementation 
 * @author Anton Belevich
 * @since 3.2.0	
 */
public class InplaceSelectBaseRenderer extends ComboBoxBaseRenderer{
	
    private static Log logger = LogFactory.getLog(InplaceSelectBaseRenderer.class);
    private static final String RICH_INPLACE_SELECT_CLASSES = "rich-inplace-select-item rich-inplace-select-font";
    private static final String CONTROLS_FACET = "controls";
    private static final String EMPTY_DEFAULT_LABEL = "&#160;&#160;&#160;";

    
    @Override
    protected void doDecode(FacesContext context, UIComponent component) {
		UIInplaceSelect inplaceInput = null;
	
		if (component instanceof UIInplaceSelect) {
		    inplaceInput = (UIInplaceSelect) component;
		} else {
		    if (logger.isDebugEnabled()) {
			logger.debug("No decoding necessary since the component " + component.getId() + " is not an instance or a sub class of UIInplaceSelect");
		    }
		    return;
		}
	
		if (InputUtils.isDisabled(inplaceInput) || InputUtils.isReadOnly(inplaceInput)) {
		    if (logger.isDebugEnabled()) {
			logger.debug(("No decoding necessary since the component " + component.getId() + " is disabled"));
		    }
		}
	
		String clientId = component.getClientId(context);
		if (clientId == null) {
		    throw new NullPointerException("component " + inplaceInput.getClientId(context) + " client id is NULL");
		}
	
		clientId = clientId + "inplaceValue";
		Map request = context.getExternalContext().getRequestParameterMap();
		if (request.containsKey(clientId)) {
		    String newValue = (String) request.get(clientId);
		    if(newValue != null) {
		    	inplaceInput.setSubmittedValue(newValue);
		    }
		}
    }

    protected boolean isAcceptableComponent(UIComponent component) {
    	if (component instanceof UIInplaceSelect) {
    		return true;
    	}
    	return false;
    }
       
    public List encodeItems(FacesContext context, UIComponent component) throws IOException {
    	   	
    	if (!isAcceptableComponent(component)) {
			return null;
		}
    	
    	List parentList = new ArrayList();
    	UIInplaceSelect inplaceSelect = (UIInplaceSelect)component; 
    	List <String> labels = new ArrayList<String>();
		ResponseWriter writer = context.getResponseWriter();
		List<SelectItem> selectItems = SelectUtils.getSelectItems(context, inplaceSelect);
		if (!selectItems.isEmpty()) {
		    for (Iterator<SelectItem> iterator = selectItems.iterator(); iterator.hasNext();) {
				SelectItem selectItem = iterator.next();
				String value = getConvertedStringValue(context, inplaceSelect, selectItem.getValue());
				String label = selectItem.getLabel();
				labels.add(label);
				
				encodeSuggestion(writer, inplaceSelect, label, RICH_INPLACE_SELECT_CLASSES);
				
				List childList = new ArrayList();
				childList.add(label);
				childList.add(value);
				parentList.add(childList);
		    }
		}
		return parentList;
    }
    
    public void encodeControlsFacet(FacesContext context, UIComponent component) throws IOException {
		UIComponent facet = component.getFacet(CONTROLS_FACET);
		if ((facet != null) && (facet.isRendered())) {
		    renderChild(context, facet);
		}
    }

    public boolean isControlsFacetExists(FacesContext context, UIComponent component) {
		UIComponent facet = component.getFacet(CONTROLS_FACET);
		if (facet != null && facet.isRendered()) {
		    return true;
		}
		return false;
    }

    protected Class<? extends UIComponent> getComponentClass() {
    	return UIInplaceSelect.class;
    }
    
    public String getSelectedItemLabel(FacesContext context, UIInplaceSelect component) {
		String defaultLabel = null;
		Object value = component.getSubmittedValue();
		if (value == null) { 
		    value = component.getAttributes().get("value");
		} 
		if (value == null) {
		    return createDefaultLabel(component); 
		}
		defaultLabel = getItemLabel(context, component, value);
		if (defaultLabel == null) {
		    return createDefaultLabel(component);
		}
		return defaultLabel;
    }
    
    protected String getItemLabel(FacesContext context, UIComponent component, Object value) {
		String itemLabel = null;
		List<SelectItem> selectItems = SelectUtils.getSelectItems(context, component);
		if (!selectItems.isEmpty()) {
		    for(SelectItem item : selectItems) {
				if (value.equals(item.getValue())) {
				    itemLabel = item.getLabel();
				}
		    }
		}
		return itemLabel;
    }
    
    protected String createDefaultLabel(UIComponent component) {
		String defaultLabel = (String) component.getAttributes().get("defaultLabel");
		if (defaultLabel == null || defaultLabel.equals("")) {
		    defaultLabel = EMPTY_DEFAULT_LABEL;
		}
		return defaultLabel;
    }
    
    protected boolean isEmptyDefaultLabel(String defaultLabel) {
    	if (defaultLabel != null && EMPTY_DEFAULT_LABEL.equals(defaultLabel)) {
    		return true;
    	}
    	return false;
    }
}
