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

import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.portlet.faces.Bridge;

import org.ajax4jsf.portlet.AbstractAjax4jsfPortletTestCase;
import org.ajax4jsf.portlet.AjaxPortletBridge;
import org.jboss.seam.Component;
import org.jboss.seam.Seam;
import org.jboss.seam.contexts.ApplicationContext;
import org.jboss.seam.contexts.Context;
import org.jboss.seam.contexts.TestLifecycle;
import org.jboss.seam.core.Conversation;
import org.jboss.seam.core.ConversationEntries;
import org.jboss.seam.core.ConversationPropagation;
import org.jboss.seam.core.Events;
import org.jboss.seam.core.Init;
import org.jboss.seam.core.ResourceLoader;
import org.jboss.seam.faces.FacesManager;
import org.jboss.seam.faces.FacesMessages;
import org.jboss.seam.faces.FacesPage;
import org.jboss.seam.faces.Validation;
import org.jboss.seam.navigation.Pages;
import org.jboss.seam.web.Session;

/**
 * @author asmirnov
 *
 */
public abstract class AbstractSeamPortletTestCase extends
		AbstractAjax4jsfPortletTestCase {
	
	protected Bridge portletBridge;

	public AbstractSeamPortletTestCase(String name) {
		super(name);
	}

	@Override
	public void setUp() throws Exception {
		super.setUp();
		  ExternalContext externalContext = setupRequest();
		  facesContext.setExternalContext(externalContext);
		  portletBridge = new AjaxPortletBridge();
		  portletBridge.init(portletConfig);
	      Context appContext = new ApplicationContext( externalContext.getApplicationMap() );
	      installComponents(appContext);
	}
	
	protected abstract ExternalContext setupRequest();

	@Override
	public void tearDown() throws Exception {
		TestLifecycle.endTest();
		super.tearDown();
		portletBridge = null;
	}
	
	   protected void installComponents(Context appContext)
	   {
	      Init init = new Init();
	      init.setTransactionManagementEnabled(true);
	      appContext.set( Seam.getComponentName(Init.class), init );
	      installComponent(appContext, MockUserTransaction.class);	      
	      installComponent(appContext, FacesManager.class);
	      installComponent(appContext, ConversationEntries.class);
	      installComponent(appContext, FacesPage.class);
	      installComponent(appContext, Conversation.class);
	      installComponent(appContext, FacesMessages.class);
	      installComponent(appContext, Pages.class);
	      installComponent(appContext, Events.class);
	      installComponent(appContext, Validation.class);
	      installComponent(appContext, Session.class);
	      installComponent(appContext, ConversationPropagation.class);
	      installComponent(appContext, ResourceLoader.class);
	   }
	   
	   protected void installComponent(Context appContext, Class clazz)
	   {
	      appContext.set( Seam.getComponentName(clazz) + ".component", new Component(clazz) );
	   }

}
