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

import java.io.IOException;
import java.util.ArrayList;
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);
    //TODO: move duplicate constants to superclass
    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 = "\u00a0\u00a0\u00a0";

    @Override
    protected void doDecode(FacesContext context, UIComponent component) {
	UIInplaceSelect inplaceSelect = null;

	if (component instanceof UIInplaceSelect) {
	    inplaceSelect = (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;
	}
	
	String clientId = inplaceSelect.getClientId(context);
	if (clientId == null) {
	    throw new NullPointerException("component client id is NULL");
	}

	if (InputUtils.isDisabled(inplaceSelect) || InputUtils.isReadOnly(inplaceSelect)) {
	    if (logger.isDebugEnabled()) {
		logger.debug(("No decoding necessary since the component " + component.getId() + " is disabled"));
	    }
	    return;
	}
	
	Map <String,String> request = context.getExternalContext().getRequestParameterMap();
	String newValue = (String) request.get(clientId);
	if (newValue != null && newValue.length()!= 0) {
	    inplaceSelect.setSubmittedValue(newValue);
	} else {
	    inplaceSelect.setSubmittedValue(null);
	}
    }

    public List<Object> encodeItems(FacesContext context, UIComponent component) throws IOException, IllegalArgumentException {

	if (!isAcceptableComponent(component)) {
	    return null;
	}

	List<Object> parentList = new ArrayList<Object>();
	List<String> labels = new ArrayList<String>();
	
	UIInplaceSelect inplaceSelect = (UIInplaceSelect) component;
	ResponseWriter writer = context.getResponseWriter();
	List<SelectItem> selectItems = SelectUtils.getSelectItems(context, inplaceSelect);
	for (SelectItem selectItem : selectItems) {
	    String value = getConvertedStringValue(context, inplaceSelect, selectItem.getValue());
	    String label = selectItem.getLabel();
	    labels.add(label);
	    encodeSuggestion(writer, inplaceSelect, label, RICH_INPLACE_SELECT_CLASSES);
	    Object[] child = new Object[2]; 
	    child[0] = label;
	    child[1] = value;
	    parentList.add(child);
	}
	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) {
	Object submittedValue = component.getSubmittedValue();
	Object value = submittedValue != null ? getConvertedValue(context, component, submittedValue) : component.getAttributes().get("value");
	if (value == null || "".equals(value)) {
	    return createDefaultLabel(component);
	}
	return getItemLabel(context, component, value);
    }
    
    protected String getItemLabel(FacesContext context, UIComponent component, Object value) {
	String itemLabel = null;
	// TODO: SelectUtils.getSelectItems is called minimum twice during encode
	List<SelectItem> selectItems = SelectUtils.getSelectItems(context, component);
	if (!selectItems.isEmpty()) {
	    for (SelectItem item : selectItems) {
		if (value.equals(item.getValue())) {
		    itemLabel = item.getLabel();
		    break;
		}
	    }
	}
	
	if (itemLabel == null) {
	    itemLabel = createDefaultLabel(component);
	}
	
	return itemLabel;
    }
    
    protected String createDefaultLabel(UIComponent component) {
	String defaultLabel = (String) component.getAttributes().get("defaultLabel");
	if (defaultLabel == null || defaultLabel.length() == 0) {
	    defaultLabel = EMPTY_DEFAULT_LABEL;
	}
	return defaultLabel;
    }
    
    protected boolean isEmptyDefaultLabel(String defaultLabel) {
	if (EMPTY_DEFAULT_LABEL.equals(defaultLabel)) {
    		return true;
    	}
    	return false;
    }
}
