/**
 * 
 */
package org.ajax4jsf.component;

import java.lang.reflect.Method;

import javax.faces.component.NamingContainer;
import javax.faces.component.UIComponentBase;
import javax.faces.context.FacesContext;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * @author asmirnov
 *
 */
public class UIPortlet extends UIComponentBase implements NamingContainer {

    private static final Log _log = LogFactory.getLog(UIPortlet.class);
    /**
     * <p>The standard component type for this component.</p>
     */
    public static final String COMPONENT_TYPE = "org.ajax4jsf.Portlet";
    
    
    /**
     * <p>The standard component family for this component.</p>
     */
    public static final String COMPONENT_FAMILY = "org.ajax4jsf.Portlet";

    /* (non-Javadoc)
     * @see javax.faces.component.UIComponent#getFamily()
     */
    public String getFamily() {
	// TODO Auto-generated method stub
	return COMPONENT_FAMILY;
    }
    
    private String portletId = null;
    
    // ----------------------------------------------------- UIComponent Methods
    public String getClientId(FacesContext context) {
        if (portletId == null) {
            Object response = context.getExternalContext().getResponse();
            Class portletResponseClass = response.getClass();
            // Class.forName is used instead of instanceof to account for the case
            // where the porletPage tag is used in a webapp and portlet.jar is not
            // in classpath. In that scenario it will prevent ClassNotFoundException.
            try {
        	Method method = portletResponseClass.getMethod("getNamespace", new Class[]{});
                portletId = (String) method.invoke(response, new Object[]{});
            } catch (Exception e) {
        	if(_log.isDebugEnabled()){
        	    _log.debug("Response is not a portlet RenderResponse");
        	}
            }
            if(null == portletId){
        	return super.getClientId(context);
            }
        }
        return portletId;
    }

}
