package org.richfaces.renderkit;

import java.io.IOException;
import java.util.Map;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.ConverterException;

import org.ajax4jsf.javascript.JSFunctionDefinition;
import org.ajax4jsf.renderkit.HeaderResourcesRendererBase;
import org.ajax4jsf.util.InputUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.richfaces.component.UIInplaceInput;

/**
 * @author Vladimir Molotkov
 * @since 3.2.0
 * InplaceInput Base renderer implementation
 *  	
 */
public class InplaceInputBaseRenderer extends HeaderResourcesRendererBase {
	
    private static Log logger = LogFactory.getLog(InplaceInputBaseRenderer.class);
    
    private static final String CONTROLS_FACET = "controls";
    
    private static final int NORMAL_KEY = 0;
   
    private static final int HOVERED_KEY = 1;
    
    private static final int EDITABLE_KEY = 2;
    
    private static final String INPLACE_COMPONENT = "COMPONENT"; 
    
    private static final String INPLACE_CHANGED = "CHANGED"; 

    private static final String INPLACE_VIEW = "VIEW"; 

    private static final String INPLACE_EDITABLE = "EDITABLE"; 
    
    private static final String INPLACE_NORMAL = "NORMAL";
    
    private static final String INPLACE_HOVERED = "HOVERED";
    
    private static final String INPLACE_CSS_PUBLIC = "rich-inplace";
    
    private static final String INPLACE_CSS_VIEW = "view";

    private static final String INPLACE_CSS_EDITABLE = "edit";
    
    private static final String INPLACE_CSS_CHANGE = "changed";
    
    private static final String INPLACE_CSS_HOVER = "hover";
    
    private static final String EMPTY_DEFAULT_LABEL = "&#160;&#160;&#160;";

    	
    protected Class<UIInplaceInput>  getComponentClass() {
        return UIInplaceInput.class;
    }
    
    protected void doDecode(FacesContext context, UIComponent component) {
	UIInplaceInput inplaceInput = null;

	if (component instanceof UIInplaceInput) {
	    inplaceInput = (UIInplaceInput) component;
	} else {
	    if (logger.isDebugEnabled()) {
	    	
		logger.debug("No decoding necessary since the component " 
			     + component.getId() + 
			     " is not an instance or a sub class of UIInplaceInput");
	    }
	    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 + UIInplaceInput.VALUE_SUFFIX;		
	Map request = context.getExternalContext().getRequestParameterMap();
	if (request.containsKey(clientId)) {
	    String newValue = (String)request.get(clientId);
	    if (newValue != null) {
		inplaceInput.setSubmittedValue(newValue);
	    }	
	}
    }
    
    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;
    }

    public String encodeScriptAttributes(FacesContext context, UIComponent component) {
    	StringBuffer attributes = new StringBuffer();
    	attributes.append("var attributes = ");
    	
    	ScriptOptions options = new ScriptOptions(component);
    	
    	String defaultLabel = (String)component.getAttributes().get("defaultLabel");
    	if (defaultLabel == null || defaultLabel.equals("")) {
	    defaultLabel = EMPTY_DEFAULT_LABEL;
    	}
    	
    	options.addOption("defaultLabel", defaultLabel);
    	options.addOption("showControls");
    	options.addOption("editEvent");
    	options.addOption("selectOnEdit");
    	options.addOption("verticalPosition", component.getAttributes().get("controlsVerticalPosition"));
    	options.addOption("horizontalPosition", component.getAttributes().get("controlsHorizontalPosition"));
    	options.addOption("inputWidth");
    	options.addOption("minInputWidth");
    	options.addOption("maxInputWidth");
    	attributes.append(options.toScript());
    	  	
    	return attributes.toString();
    }
      
    public String encodeScriptEvents(FacesContext context, UIComponent component) {
    	StringBuffer events = new StringBuffer();
    	
    	events.append("var events = ");
    	ScriptOptions options = new ScriptOptions(component);
    	options.addEventHandler("oneditactivation");
    	options.addEventHandler("onviewactivation");
    	options.addEventHandler("oneditactivated");
    	options.addEventHandler("onviewactivated");
    	events.append(options.toScript());
    	
    	return events.toString();
    }
        
    public String encodeInplaceInputCss(FacesContext context, UIComponent component) {
    	StringBuffer cssMap = new StringBuffer();
    	cssMap.append("var classes = ");
    	
    	ScriptOptions mainMap = new ScriptOptions(component);
    	ScriptOptions componentClasses = new ScriptOptions(component);
    	ScriptOptions changedClasses = new ScriptOptions(component);
    	ScriptOptions viewClasses = new ScriptOptions(component);
   	
    	changedClasses.addOption(INPLACE_NORMAL, buildCss(component, NORMAL_KEY, INPLACE_CSS_CHANGE) );
    	changedClasses.addOption(INPLACE_HOVERED, buildCss(component, HOVERED_KEY, INPLACE_CSS_CHANGE));
    	
    	viewClasses.addOption(INPLACE_NORMAL, buildCss(component, NORMAL_KEY, INPLACE_CSS_VIEW) );;
    	viewClasses.addOption(INPLACE_HOVERED, buildCss(component, HOVERED_KEY, INPLACE_CSS_VIEW));
  	    	
    	componentClasses.addOption(INPLACE_CHANGED,changedClasses);
    	componentClasses.addOption(INPLACE_VIEW, viewClasses);
    	componentClasses.addOption(INPLACE_EDITABLE,buildCss(component, EDITABLE_KEY, INPLACE_CSS_EDITABLE));
    	
    	mainMap.addOption(INPLACE_COMPONENT, componentClasses);
    	cssMap.append(mainMap.toString());
    	return cssMap.toString(); 
	}
    
    private String buildCss(UIComponent component, int key, String suffix) {
    	Object value;
    	StringBuffer stringBuffer = new StringBuffer();
    	
    	switch (key) {
	case NORMAL_KEY:
	    stringBuffer.append(INPLACE_CSS_PUBLIC);
	    stringBuffer.append(" ");
	    stringBuffer.append(INPLACE_CSS_PUBLIC + "-" + suffix);
	    value = component.getAttributes().get(suffix + "Class");
	    if (value != null) {
		stringBuffer.append(" ");
		stringBuffer.append(value);
	    }
	    break;
	case HOVERED_KEY:
	    stringBuffer.append(INPLACE_CSS_PUBLIC + "-" + "input-" + suffix + "-" + INPLACE_CSS_HOVER);
	    value = component.getAttributes().get(suffix + "HoverClass");
	    if (value != null) {
		stringBuffer.append(" ");
		stringBuffer.append(value);
	    }
	    break;

	case EDITABLE_KEY:
	    stringBuffer.append(INPLACE_CSS_PUBLIC);
	    stringBuffer.append(" ");
	    stringBuffer.append(INPLACE_CSS_PUBLIC + "-" + suffix);
	    value = component.getAttributes().get(suffix + "Class");
	    if (value != null) {
		stringBuffer.append(" ");
		stringBuffer.append(value);
	    }
	    break;	
    	}
       	return stringBuffer.toString();
    }
    
    public String getAsEventHandler(FacesContext context, UIComponent component, String attributeName) {
		String event = (String) component.getAttributes().get(attributeName);
		String result = null;
		
		if (event != null) {
			event = event.trim();
		
			if (event.length() != 0) {
				JSFunctionDefinition function = new JSFunctionDefinition();
				function.addParameter("event");
				function.addToBody(event);
	
				result = function.toScript();
			}
		}
		return result;
    }
    
    @Override
    public Object getConvertedValue(FacesContext context, UIComponent component, Object submittedValue) throws ConverterException {
	return InputUtils.getConvertedValue(context, component, submittedValue); 
    }
    
    protected String getConvertedStringValue(FacesContext context, UIInplaceInput component, Object value) {
	return InputUtils.getConvertedStringValue(context, component, value);
    }
    
    protected boolean isEmptyDefaultLabel(String defaultLabel) {
    	if (defaultLabel != null && EMPTY_DEFAULT_LABEL.equals(defaultLabel)) {
    		return true;
    	}
    	return false;
    }
}
