package com.n2bb.action;

import java.security.Principal;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.tandbergtv.workflow.auth.AuthorizationManager;
import com.tandbergtv.workflow.auth.Credentials;
import com.tandbergtv.workflow.auth.IAuthorizationManager;
import com.tandbergtv.workflow.web.common.StaticCodes;

/**
 * Goes to the configurable home page for whole webapp.
 *
 *  To set home page for whole web app, put this in plugin-myModule.xml
 *   immediately after <web-plugin>:
 *     <context-params>
 *        <update>
 *        <context-param>
 *            <param-name>global.homepage</param-name>
 *            <param-value>/myModule/home.jsp</param-value>
 *        </context-param>
 *        </update>
 *    </context-params>
 * @author kmatsuoka
 * @version $Id: HomeAction.java,v 1.5 2006/08/28 20:57:24 rao Exp $
 */
public class HomeAction extends Action {
	
	private static final String SUCCESS_FORWARD = "success";
	
	private static final String FAILURE_FORWARD = "logout";
	
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		ServletContext servletContext = servlet.getServletContext();
		String homepage = servletContext.getInitParameter("global.homepage");
		if (homepage != null)
			return new ActionForward(homepage);
		
		Principal principal = request.getUserPrincipal();
		
		if (principal == null)
			return mapping.findForward(FAILURE_FORWARD);

		/*
		 * We have to set the credentials at this point before we transfer control to the actual
		 * workflow module because the Struts RequestProcessor for that module checks to see if
		 * the credentials are present
		 */
		IAuthorizationManager manager = AuthorizationManager.getInstance();
		Credentials credentials = manager.getCredentials(principal);
		request.getSession().setAttribute(StaticCodes.USER_CREDENTIALS, credentials);
		
		return mapping.findForward(SUCCESS_FORWARD);
	}
}
