/**
 * 
 */
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;
import org.richfaces.json.JSONArray;

/**
 * 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 JSONArray jsonParentArray;


    @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);
	    }
	}
    }

    public void encodeItems(FacesContext context, UIComponent component) throws IOException {
	List <String> labels = new ArrayList<String>();
	ResponseWriter writer = context.getResponseWriter();
	jsonParentArray = new JSONArray();
 	
	List<SelectItem> selectItems = SelectUtils.getSelectItems(context, component);
	if (!selectItems.isEmpty()) {
	    for (Iterator<SelectItem> iterator = selectItems.iterator(); iterator.hasNext();) {
		SelectItem selectItem = iterator.next();
		String value = getConvertedStringValue(context, component, selectItem.getValue());
		String label = selectItem.getLabel();
		labels.add(label);
		
		encodeSuggestion(writer, component, label, RICH_INPLACE_SELECT_CLASSES);
		
		JSONArray jsonChildArray = new JSONArray();
		jsonChildArray.put(label);
		jsonChildArray.put(value);
		jsonParentArray.put(jsonChildArray);
	    }
	}
	setValuesList(labels);
    }
    
    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 getItemsTextAsJSArray(FacesContext context, UIComponent component) {
	StringBuffer attributes = new StringBuffer();
    	attributes.append(jsonParentArray.toString());
    	return attributes.toString();
    }
    
    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 = "\u00a0\u00a0\u00a0";    
	}
	return defaultLabel;
    }
}
