/**
 * License Agreement.
 *
 * Rich Faces - Natural Ajax for Java Server Faces (JSF)
 *
 * Copyright (C) 2007 Exadel, Inc.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License version 2.1 as published by the Free Software Foundation.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
 */
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.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;
	List<SelectItem> selectItems = SelectUtils.getSelectItems(context, inplaceSelect);
	for (SelectItem selectItem : selectItems) {
	    String value = getConvertedStringValue(context, inplaceSelect, selectItem.getValue());
	    String label = selectItem.getLabel().trim();
	    labels.add(label);
	    encodeSuggestion(context, 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) {
//    String selectedItemLabel = (String)component.getSubmittedValue();
//    if(selectedItemLabel == null || !component.isValid()) {
//		Object value = component.getAttributes().get("value");
//		if (value == null || "".equals(value)) {
//			selectedItemLabel = createDefaultLabel(component);
//		} else {
//			selectedItemLabel = getItemLabel(context, component, value);
//		}
//	}
//	return selectedItemLabel;
//    }
    
    protected String getItemLabel(FacesContext context, UIInplaceSelect component, Object value) {
	String itemLabel = null;
	// TODO: SelectUtils.getSelectItems is called minimum twice during encode
	if(value != null) {
		List<SelectItem> selectItems = SelectUtils.getSelectItems(context, component);
		if (!selectItems.isEmpty()) {
			for (SelectItem item : selectItems) {
				if (value.equals(item.getValue())) {
					itemLabel = component.isShowValueInView() ? getConvertedStringValue(context, component, item.getValue()) : item.getLabel();
					break;
				}
			}
		}
	}

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