package org.richfaces.renderkit;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
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.convert.ConverterException;
import javax.faces.model.SelectItem;

import org.ajax4jsf.javascript.JSFunctionDefinition;
import org.ajax4jsf.javascript.ScriptUtils;
import org.ajax4jsf.renderkit.HeaderResourcesRendererBase;
import org.ajax4jsf.renderkit.RendererUtils.HTML;
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.UIComboBox;

/**
 * @author Anton Belevich
 * @since 3.2.0
 * ComboBox Base renderer implementation
 *  	
 */
public class ComboBoxBaseRenderer extends HeaderResourcesRendererBase {
	
    private static final String RICH_COMBOBOX_ITEM_CLASSES = "rich-combobox-item rich-combobox-item-normal";
    private static Log logger = LogFactory.getLog(ComboBoxBaseRenderer.class);

    protected Class<? extends UIComponent> getComponentClass() {
    	return UIComboBox.class;
    }

    protected void doDecode(FacesContext context, UIComponent component) {
	UIComboBox comboBox = null;

	if (component instanceof UIComboBox) {
	    comboBox = (UIComboBox) component;
	} else {
	    if (logger.isDebugEnabled()) {
		logger.debug("No decoding necessary since the component " + component.getId() + " is not an instance or a sub class of UIComboBox");
	    }
	    return;
	}
	
	String clientId = comboBox.getClientId(context);
	if (clientId == null) {
	    throw new NullPointerException("component client id is NULL");
	}

	if (InputUtils.isDisabled(comboBox) || InputUtils.isReadOnly(comboBox)) {
	    if (logger.isDebugEnabled()) {
	    	logger.debug(("No decoding necessary since the component " + component.getId() + " is disabled"));
	    }
	}

	Map <String, String> request = context.getExternalContext().getRequestParameterMap();
	String newValue = (String) request.get(clientId);
	if (newValue != null) {
	    comboBox.setSubmittedValue(newValue);
	}
    }
    
    public List<Object> encodeItems(FacesContext context, UIComponent component) throws IOException, IllegalArgumentException {
	if (!isAcceptableComponent(component)) {
	    return null;
	}

	UIComboBox comboBox = (UIComboBox) component;
	Object suggestionValues = comboBox.getSuggestionValues();
	ResponseWriter writer = context.getResponseWriter();
	List <Object>values = encodeSuggestionValues(context, component, writer, suggestionValues);
	List<SelectItem> selectItems = SelectUtils.getSelectItems(context, component);
	for (SelectItem selectItem : selectItems) {
	    String value = getConvertedStringValue(context, comboBox, selectItem.getValue());
	    values.add(value);
	    encodeSuggestion(writer, comboBox, value, RICH_COMBOBOX_ITEM_CLASSES);
	    
	}
	return values;
    }
    
    public List<Object> encodeSuggestionValues(FacesContext context, UIComponent component, ResponseWriter writer,
	    Object suggestionValues) throws IOException, IllegalArgumentException {
	ArrayList<Object> values = new ArrayList<Object>();
	if (suggestionValues != null) {
	    if (suggestionValues instanceof Collection) {
		Collection<Object> collection = (Collection) suggestionValues;
		for (Object suggestionValue : collection) {
		    String value = getConvertedStringValue(context, component, suggestionValue);
		    values.add(value);
		    encodeSuggestion(writer, component, value, RICH_COMBOBOX_ITEM_CLASSES);
		}
	    } else if (suggestionValues.getClass().isArray()) {
		Object[] suggestions = (Object[]) suggestionValues;
		for (int i = 0; i < suggestions.length; i++) {
		    String value = getConvertedStringValue(context, component, suggestions[i]);
		    values.add(value);
		    encodeSuggestion(writer, component, value, RICH_COMBOBOX_ITEM_CLASSES);
		}
	    } else {
		throw new IllegalArgumentException("suggestionValues should be Collection or Array");
	    }
	}
	return values;
    }

    @Override
    public Object getConvertedValue(FacesContext context, UIComponent component, Object submittedValue) throws ConverterException {
    	return InputUtils.getConvertedValue(context, component, submittedValue);
    }

    protected String getConvertedStringValue(FacesContext context, UIComponent component, Object value) {
    	return InputUtils.getConvertedStringValue(context, component, value);
    }

    public void encodeSuggestion(ResponseWriter writer, UIComponent component, String value, String classes) throws IOException {
	writer.startElement(HTML.SPAN_ELEM, component);
	writer.writeAttribute(HTML.class_ATTRIBUTE, classes, null);
	writer.writeText(value, null);
	writer.endElement(HTML.SPAN_ELEM);
    }
    
    protected boolean isAcceptableComponent(UIComponent component) {
    	return component != null && this.getComponentClass().isAssignableFrom(component.getClass());
    }
    
    public String getItemsTextAsJSArray(FacesContext context, UIComponent component, List items) {
    	return ScriptUtils.toScript(items);
    }

    public String getAsEventHandler(FacesContext context, UIComponent component, String attributeName) {
	JSFunctionDefinition script = getUtils().getAsEventHandler(context, component, attributeName, null);  
	return ScriptUtils.toScript(script);
    }
    
    public String encodeValue(String value){
	return ScriptUtils.toScript(value);     
    }
}
