/**
 * 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.ajax4jsf.taglib.html.jsp;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.el.ReferenceSyntaxException;
import javax.faces.el.ValueBinding;
import javax.faces.webapp.UIComponentTag;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.Tag;
import javax.servlet.jsp.tagext.TagSupport;

import org.ajax4jsf.Messages;
import org.ajax4jsf.event.AjaxListener;
import org.ajax4jsf.event.AjaxListenerHelper;
import org.ajax4jsf.event.AjaxSource;


/**
 * @author shura
 * 
 * Custom tag for append AJAX request listeners to AjaxContainer.
 *  
 */
public class AjaxListenerTag extends TagSupport {

    /**
     * 
     */
    private static final long serialVersionUID = 2576519366310474212L;
    /**
     * class name for ajax events listener.   
     */
    private String type = null;
    
    private String binding = null;

    /**
     *  
     */
    public AjaxListenerTag() {
    }

    public void setType(String type) {
        this.type = type;
    }

    /**
	 * @param binding the binding to set
	 */
	public void setBinding(String binding) {
		this.binding = binding;
	}

	public int doStartTag() throws JspException {
        if (type == null) {
            throw new JspException(Messages.getMessage(Messages.NULL_TYPE_ATTRIBUTE_ERROR));
        }

        //Find parent UIComponentTag
        UIComponentTag componentTag = UIComponentTag
                .getParentUIComponentTag(pageContext);
        if (componentTag == null) {
            throw new JspException(
            		Messages.getMessage(Messages.NO_UI_COMPONENT_TAG_ANCESTOR_ERROR, "AjaxListenerTag"));
        }

        if (componentTag.getCreated()) {
            //Component was just created, so we add the Listener
            UIComponent component = componentTag.getComponentInstance();
            if (component instanceof AjaxSource) {
                AjaxListener listener;
                if(null != binding){
                	ValueBinding valueBinding;
                	try {
					valueBinding = FacesContext.getCurrentInstance().getApplication().createValueBinding(binding);
                	} catch (ReferenceSyntaxException e) {
						throw new JspException(e);
					}
                	listener = new AjaxListenerHelper(valueBinding);
                } else {
                String className;
                if (UIComponentTag.isValueReference(type)) {
                    FacesContext facesContext = FacesContext
                            .getCurrentInstance();
                    ValueBinding valueBinding = facesContext.getApplication()
                            .createValueBinding(type);
                    className = (String) valueBinding.getValue(facesContext);
                } else {
                    className = type;
                }
				try {
					listener = (AjaxListener) Class.forName(className).newInstance();
				} catch (Exception e) {
	                throw new JspException(Messages.getMessage(Messages.INSTANTIATE_LISTENER_ERROR, className, component.getId()), e);
				} 
                }
                ((AjaxSource) component).addAjaxListener(listener);
            } else {
                throw new JspException(Messages.getMessage(Messages.NOT_PARENT_AJAX_COMPONENT_ERROR, component.getId()));
            }
        }

        return Tag.SKIP_BODY;
    }

}
