package org.richfaces.renderkit;

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

import org.ajax4jsf.javascript.JSFunctionDefinition;
import org.ajax4jsf.javascript.JSReference;
import org.ajax4jsf.javascript.ScriptString;
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 List valuesList = null;
    private 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;
	}

	if (InputUtils.isDisabled(comboBox) || InputUtils.isReadOnly(comboBox)) {
	    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 " + comboBox.getClientId(context) + " client id is NULL");
	}

	clientId = clientId + "comboboxValue";
	Map request = context.getExternalContext().getRequestParameterMap();
	if (request.containsKey(clientId)) {
	    String newValue = (String) request.get(clientId);
	    comboBox.setSubmittedValue(newValue);
	}
    }

    public void encodeItems(FacesContext context, UIComponent component) throws IOException {
	UIComboBox comboBox = (UIComboBox) component;
	Object suggestionValues = comboBox.getSuggestionValues();
	ResponseWriter writer = context.getResponseWriter();

	List values = new ArrayList();

	if (suggestionValues != null) {
	    if (suggestionValues instanceof Collection) {
		for (Iterator iterator = ((Collection) suggestionValues).iterator(); iterator.hasNext();) {
		    String value = getConvertedStringValue(context, comboBox, iterator.next());
		    values.add(value);
		    encodeSuggestion(writer, comboBox, 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, comboBox, suggestions[i]);
		    values.add(value);
		    encodeSuggestion(writer, comboBox, value, RICH_COMBOBOX_ITEM_CLASSES);
		}
	    } else {
		throw new IllegalArgumentException("suggestionValues should be Collection or array");
	    }

	}

	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, comboBox, selectItem.getValue());
		values.add(value);
		encodeSuggestion(writer, comboBox, value, RICH_COMBOBOX_ITEM_CLASSES);
	    }
	}
	setValuesList(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.write(value);
	writer.endElement(HTML.SPAN_ELEM);
    }

    public String getItemsTextAsJSArray(FacesContext context, UIComponent component) {
	return ScriptUtils.toScript(valuesList);
    }

    public String getAsEventHandler(FacesContext context, UIComponent component, String attributeName) {
	String event = (String) component.getAttributes().get(attributeName);
	ScriptString result = JSReference.NULL;

	if (event != null) {
	    event = event.trim();
	    if (event.length() != 0) {
		JSFunctionDefinition function = new JSFunctionDefinition();
		function.addParameter("event");
		function.addToBody(event);
		result = function;
	    }
	}
	
	return ScriptUtils.toScript(result);
    }

    public List getValuesList() {
	return valuesList;
    }

    public void setValuesList(List valuesList) {
	this.valuesList = valuesList;
    }
}
