/**
 * 
 */
package org.ajax4jsf.portlet.lifecycle;

import javax.faces.FacesException;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseListener;
import javax.faces.lifecycle.Lifecycle;

import org.jboss.seam.jsf.SeamPhaseListenerWrapper;

/**
 * @author asmirnov
 *
 */
public class SeamPortletLifecycle extends PortletLifecycle {
	
	public static final String SEAM_PORTLET_LIFECYCLE = "SEAM_PORTLET";
	public static final String SEAM_PHASE_LISTENER_CLASS = "org.jboss.seam.jsf.SeamPhaseListener";

	
	private PhaseListener seamListener;
	
	private SeamPhaseListenerWrapper seamListenerWrapper;


    /**
     * @param listener
     * @see javax.faces.lifecycle.Lifecycle#addPhaseListener(javax.faces.event.PhaseListener)
     */
    public void addPhaseListener(PhaseListener listener) {
			// Existing Seam 2.0 releases hack - replace SeamPhaseListener by our bridge-compatible version.
			if(SEAM_PHASE_LISTENER_CLASS.equals(listener.getClass().getName())){
				if(null == seamListener){
					seamListener = listener;
					seamListenerWrapper = new SeamPhaseListenerWrapper(listener);
					addPhaseListener(0, seamListenerWrapper);
				} else {
					throw new FacesException("Attempt to register second SeamPhaseListener");
				}
			} else {
				super.addPhaseListener(listener);
			}
    }





	/**
	 * @param listener
	 * @see javax.faces.lifecycle.Lifecycle#removePhaseListener(javax.faces.event.PhaseListener)
	 */
	public void removePhaseListener(PhaseListener listener) {
		if(listener == this.seamListener){
			listener = seamListenerWrapper;
			seamListener = seamListenerWrapper = null;
		}
		super.removePhaseListener(listener);
	}



    
}
