/*
 * $Id: CaptureAccountAction.java,v 1.17 2007/08/08 12:14:55 marbobo Exp $
 *
 * Copyright (c) Siemens AG 2008 
 *           (c) Universität Paderborn 2008 
 * Licensed under EUPL 1.1. 
 *
 * $Log: CaptureAccountAction.java,v $
 * Revision 1.17  2007/08/08 12:14:55  marbobo
 * + License-Funktionalität komplett umgeschrieben
 * + Bugfix bzgl. Beschreibungsfelder von Entitäten
 * + Bugfix mailing
 *
 * Revision 1.16  2006/10/04 03:14:32  marbobo
 * + Vollständige Unterstützung für Templates implementiert
 * + Alles von Virtoweb auf ProCoBa umgestellt
 *
 * Revision 1.15  2006/04/29 18:39:45  marbobo
 * + Refactoriengs und eine Ausgaben vereinheitlicht
 *
 * Revision 1.14  2006/03/23 11:45:58  marbobo
 * + Mögliche NPE abgefangen
 *
 * Revision 1.13  2006/02/27 16:16:05  marbobo
 * + Systemsichten hinzugefügt
 * + SysLinks angepasst
 * + Benutzer können falls gewünscht Dokumentqueries anlegen
 *
 * Revision 1.12  2005/12/16 11:50:31  lawern
 * *** empty log message ***
 *
 * Revision 1.11  2005/10/03 17:34:20  marbobo
 * + Nur zur Projektsicht leiten wenn Projektmanagment aktiv ist
 *
 * Revision 1.10  2005/09/01 08:31:58  korowa
 * Es werden mehrere URL angeboten, welche direkten Zugriff auf Dateien
 *  und automatisches Anmelden als Gast erlauben.
 *
 * Revision 1.9  2005/03/16 15:48:47  jonyp
 * getLastnameLabel for user tracking infos
 *
 * Revision 1.8  2005/03/16 15:10:13  jonyp
 * *** empty log message ***
 *
 * Revision 1.7  2005/02/14 14:01:53  bigmac
 * Applikationsweites CSS konfigurierbar gemacht + Refactorings
 *
 * Revision 1.6  2004/11/02 21:42:29  marbobo
 * + Einige Funktionen für Gast-Benutzer gesperrt
 * + WebShare.LOGIN_PAGE mit WebShare.getLoginPage() ersetzt
 *
 * Revision 1.5  2004/06/27 17:36:00  marbobo
 * + Quellcode maintenance
 *
 * Revision 1.4  2004/05/06 15:10:48  jonyp
 * check if prevUser is not null ==> catch NPE
 *
 * Revision 1.3  2004/04/01 20:51:32  marbobo
 * Anpassungen an SysLink
 *
 * Revision 1.2  2004/04/01 13:33:05  jonyp
 * deleted unused imports
 *
 * Revision 1.1  2004/04/01 09:39:25  jonyp
 * first strike
 *
 */
package vkc.view.action;

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 vkc.db.entities.VKCUser;
import vkc.db.entities.VKCCategory;
import vkc.db.serializer.VKCSysParameterSerializer;
import vkc.db.serializer.VKCUserSerializer;

import vkc.misc.VKCLogManager;

import vkc.util.ServletUtils;
import vkc.view.PageId;
import vkc.view.WebShare;
import vkc.view.bean.UserTrackingInfo;
import vkc.view.form.SysLinkForm;

import java.sql.Timestamp;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * class for the control of capturing accounts
 *
 * @author jonyP
 */
public final class CaptureAccountAction extends Action {
	private ActionForward INFO_FORWARD = new ActionForward("/templates/${template.name}/common/InfoPage.jsp");
    
    public ActionForward execute(ActionMapping mapping, 
            					 ActionForm form,
            					 HttpServletRequest request, 
            					 HttpServletResponse response)
    throws Exception {
        // abfrage, das das nur ein admin darf...
        HttpSession session = request.getSession();

        // get the user, who wants to capture an account
        VKCUser prevUser = (VKCUser) session.getAttribute(WebShare.USER_KEY);
        
		// check, if the capturer has enough privileges...that means: must be an admin
		if (prevUser == null || !prevUser.hasAdminPrivileges()) {
			request.setAttribute(WebShare.INFO_KEY, "vkc.info.action_not_allowed");
			
			return INFO_FORWARD;
		}
        
        // load account, which should be captured, from db
        VKCUser user = null;

        try {
            user = VKCUserSerializer.retrieveUser(new Integer(request.getParameter("userId")));
        } catch (Exception ex) {
            servlet.log("Could not retrieve User from DB:\n" + ex.toString());
			request.setAttribute(WebShare.INFO_KEY, "vkc.error.exceptionOccured");
			
			return INFO_FORWARD;
        }

        ServletUtils.removeSessionAttributes(session);
        
        // save previousUser in session
		session.setAttribute(WebShare.PREV_USER_KEY, prevUser);

        // save captureUser as new User in session
		if (user.getSessionTimeout() != null && user.getSessionTimeout().intValue() != 0) {
			// Session-Timeout setzen
			session.setMaxInactiveInterval(user.getSessionTimeout().intValue() * 60);
		}
        
        Timestamp loginTime = new Timestamp(System.currentTimeMillis());
        user.setMostRecentLogin(loginTime);
        session.setAttribute(WebShare.USER_KEY, user);
        session.setAttribute(WebShare.LOCALE_KEY, user.getLanguage().getLocale());

        // change language
        setLocale(request, user.getLanguage().getLocale());

        String log = "User '" + prevUser.getUser() + "' captured account of User '" + user.getUser() + "'";
		log +=  " (userId = " +  user.getUserId() + ", session timeout = " + (session.getMaxInactiveInterval() / 60) + "min)";

        VKCLogManager.infoLog(this, log);

        UserTrackingInfo bean = new UserTrackingInfo(user.getUserId(),
                                                     user.getLastnameLabel(),
                									 request.getSession(), 
                									 request.getRemoteAddr(), 
                									 new Date(loginTime.getTime()));

        session.setAttribute(WebShare.USER_TRACKING_KEY, bean);
        session.setAttribute(WebShare.SYSTEMVIEWTYPEID_KEY, user.getSystemViewTypeId());

        //Procoba-Start
        if (PageId.FUNCTIONAL_VIEW.equals(user.getSystemViewTypeId()) && VKCSysParameterSerializer.isProjectManagementEnabled()) {
			return new ActionForward(SysLinkForm.getProcobaFunctionalSysLink());
        }

		if (PageId.PROJECT_VIEW.equals(user.getSystemViewTypeId()) && VKCSysParameterSerializer.isProjectManagementEnabled()) {
			return new ActionForward(SysLinkForm.getProcobaProjectSysLink());
		} 

		//by default: startCategory is root
		Integer startCategoryId = new Integer(VKCCategory.ROOT_CATEGORY_ID); 
	    
		// if user has another take it...
		if (user.getHomeCategoryId() != null && user.getHomeCategoryId().intValue() > VKCCategory.ROOT_CATEGORY_ID) {
			startCategoryId = user.getHomeCategoryId();
		}

		return new ActionForward(SysLinkForm.getCategorySysLink(startCategoryId, SysLinkForm.LOGINTYPE_NORMAL_USER), true);
    }
}