/*
 * $Id: LoginLicenseAction.java,v 1.6 2007/08/08 12:14:54 marbobo Exp $
 *
 * Copyright (c) Siemens AG 2008 
 *           (c) Universität Paderborn 2008 
 * Licensed under EUPL 1.1. 
 * 
 * $Log: LoginLicenseAction.java,v $
 * Revision 1.6  2007/08/08 12:14:54  marbobo
 * + License-Funktionalität komplett umgeschrieben
 * + Bugfix bzgl. Beschreibungsfelder von Entitäten
 * + Bugfix mailing
 *
 */
package vkc.view.action;

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

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

import org.apache.struts.Globals;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import vkc.db.entities.VKCCategory;
import vkc.db.entities.VKCLanguage;
import vkc.db.entities.VKCUser;
import vkc.db.serializer.VKCLanguageSerializer;
import vkc.db.serializer.VKCLicenseSerializer;
import vkc.db.serializer.VKCSysParameterSerializer;
import vkc.db.serializer.VKCUserSerializer;
import vkc.exception.DBException;
import vkc.ldap.VKCLdapUser;
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.LoginLicenseForm;
import vkc.view.form.SysLinkForm;

public class LoginLicenseAction extends Action {
    private ActionForward DEFAULT_FORWARD = new ActionForward("/templates/${template.name}/common/loginLicense.jsp");
    private ActionForward INFO_FORWARD = new ActionForward("/templates/${template.name}/common/InfoPage.jsp");

    public ActionForward execute(ActionMapping mapping, 
                                 ActionForm f,
                                 HttpServletRequest request, 
                                 HttpServletResponse response)
    throws Exception {
        if (Integer.parseInt(WebShare.getSysParameterValue("LICENSE", "EnableLicensemanagement", "0")) == 0) {
            request.setAttribute( WebShare.INFO_KEY, "vkc.info.action_not_allowed" );
            
            return INFO_FORWARD;
        }

        LoginLicenseForm form = (LoginLicenseForm) f;
        
        if (form.getUser() == null) {
            return new ActionForward(WebShare.getLoginPage(), true);
        }

        if (request.getParameter("action.accept.license") != null) {
            return handleAcceptLicenseAction(form, request);
        } else if (request.getParameter("action.decline.license") != null) {
            return handleDeclineLicenseAction(form, request);
        }

        return DEFAULT_FORWARD;
    }

    private ActionForward handleAcceptLicenseAction(LoginLicenseForm form, HttpServletRequest request) throws DBException {
        ActionErrors errors = new ActionErrors();
        HttpSession session = request.getSession();
        VKCUser user = form.getUser();

        if (user.isGuestUser()) {
            // alle Objekte aus der Session entfernen
            ServletUtils.removeSessionAttributes(session);

            if (request.getLocale() == null) {
                VKCLanguage lang = VKCLanguageSerializer.getDefaultLanguage();
                user.setLanguage(lang);
                setLocale(request, lang.getLocale());
            } else {
                VKCLanguage lang = VKCLanguageSerializer.getLanguageByShortName(request.getLocale().getLanguage());
                
                if (lang != null) {
                    user.setLanguage(lang);
                    setLocale(request, lang.getLocale());
                } else {
                    lang = VKCLanguageSerializer.getDefaultLanguage();
                    user.setLanguage(lang);
                    setLocale(request, lang.getLocale());
                }
            }

            Timestamp loginTime = new Timestamp(System.currentTimeMillis());
            user.setMostRecentLogin(loginTime);
            session.setAttribute(WebShare.USER_KEY, user);
            session.setAttribute(WebShare.LOCALE_KEY, user.getLanguage().getLocale());

            String log = "User 'guest' logged on in session " + session.getId() + " with locale: " + user.getLanguage().getLocale();

            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());

            //externer Linkaufruf
            if (form.isSysLink()) {
                return new ActionForward(form.getSysLink());
            }

            return new ActionForward(WebShare.HOME_PAGE, true);
        }

        if (!(user instanceof VKCLdapUser)) {
            // Die vom User akzeptierte License erneuern
            VKCLicenseSerializer.saveUserLicense(user.getUserId(), form.getLicense().getLicenseId());

            // nur wenn user ein interner User ist, dann nachfolgende aktionen ausführen
             if (!user.isPasswordChanged()) {
                errors.add("password.neverchanged", new ActionError("error.password.neverchanged"));
                session.setAttribute(Globals.ERROR_KEY, errors);
                request.getSession().setAttribute(WebShare.TEMP_USER_KEY, user);
                
                return new ActionForward("/loginChangePassword.do", false);
            }
        
       
            
            //Zur aktuellen Nachrichtenseite weiterleiten
            if (VKCSysParameterSerializer.retrieveIntValue("NEWS", "EnableNews", 0) != 0) {
                if (user.hasUnreadNews()) {
                    request.getSession().setAttribute(WebShare.TEMP_USER_KEY, user);
                    
                    return new ActionForward("/showRecentNewsFrameset.do", false);
                }
            }
        }  

        // Session-Timeout setzen
        if (user.getSessionTimeout() != null && user.getSessionTimeout().intValue() != 0) {
            session.setMaxInactiveInterval(user.getSessionTimeout().intValue() * 60);
        }
        
        // Eingeloggten User in der Session speichern
        vkc.util.ServletUtils.removeSessionAttributes(session);
        Timestamp loginTime = new Timestamp(System.currentTimeMillis());
        user.setMostRecentLogin(loginTime);
        session.setAttribute(WebShare.USER_KEY, user);
        session.setAttribute(WebShare.LOCALE_KEY, user.getLanguage().getLocale());

        // Sprache wechseln
        setLocale(request, user.getLanguage().getLocale());

        String log = user.getUserDescription();
        log += " logged in (" + "userId = " +  user.getUserId();
        log += ", session timeout = " + (session.getMaxInactiveInterval() / 60) + "min)";

        // track users login time
        VKCUserSerializer.saveMostRecentLogin(user.getUserId());

        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());
        
        //externer Linkaufruf
        if (form.isSysLink()) {
            return new ActionForward(form.getSysLink());
        }

        //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);
    }

    private ActionForward handleDeclineLicenseAction(LoginLicenseForm form, HttpServletRequest request) {
        request.getSession().removeAttribute(Globals.ERROR_KEY);
        request.getSession().removeAttribute(WebShare.TEMP_USER_KEY);
        
        return new ActionForward(WebShare.getLoginPage(), false);
    }
}