/*
 * Copyright
 *   2007 axYus - www.axyus.com
 *
 * This file is part of XEMELIOS.
 *
 * XEMELIOS is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * XEMELIOS is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with XEMELIOS; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

package fr.gouv.finances.dgfip.xemelios.web.connexion;

import fr.gouv.finances.dgfip.xemelios.auth.AuthEngine;
import fr.gouv.finances.dgfip.xemelios.auth.XemeliosUser;
import fr.gouv.finances.dgfip.xemelios.services.XemeliosHelper;
import fr.gouv.finances.dgfip.xemelios.web.AttributeHelper;
import fr.gouv.finances.dgfip.xemelios.web.utils.StdDispatchAction;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.apache.struts.Globals;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

/**
 * @author CBO
 */
public class ConnexionAction extends StdDispatchAction {

    static private final ThreadLocal threadLocalRequestHolder = new ThreadLocal();
    private static final Logger logger = Logger.getLogger(StdDispatchAction.class);

    static public ThreadLocal getThreadLocalRequestHolder() {
        return ConnexionAction.threadLocalRequestHolder;
    }

    @Override
    public ActionForward unspecified(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
        // On nettoie la session tout en conservant l'éventuel message d'erreur :
        ActionMessages actionMessages = (ActionMessages) request.getSession().getAttribute(Globals.ERROR_KEY);
        request.getSession().invalidate();
        if (actionMessages != null) {
            request.getSession().setAttribute(Globals.ERROR_KEY, actionMessages);
        }
        if (getAuthEngine().isLoginRequired() || getAuthEngine().isPasswordRequired()) {
            // Le systeme d'authentification nécessite une saisie de l'utilisateur, on redirige vers une page de saisie :
            return displayUserUI(mapping, request);
        } else {
            // Le systeme d'authentification ne nécessite pas de saisie de l'utilisateur, on l'interroge donc directement.
            // Pour les SSO transmettant des informations dans la requete on rend accessible, le temps de l'interrogation, l'objet Request :
            getThreadLocalRequestHolder().set(request);
            XemeliosUser user = getAuthEngine().createUser(null, null);
            // Une fois l'authentification effectuée on retire l'objet Request :
            getThreadLocalRequestHolder().remove();
            if (user != null) {
                return processSuccessfullAuthentification(mapping, request, user);
            } else {
                // Echec définitif :
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
                return null;
            }
        }
    }

    public ActionForward processUserInputs(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
        final ConnexionForm connexionForm = (ConnexionForm) form;
        XemeliosUser user = getAuthEngine().createUser(
                getAuthEngine().isLoginRequired() ? connexionForm.getLogin() : null,
                getAuthEngine().isPasswordRequired() ? connexionForm.getPassword() : null);
        if (user != null) {
            return processSuccessfullAuthentification(mapping, request, user);
        } else {
            ActionMessages errors = new ActionMessages();
            errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("connexion.erreur.authentificationFail"));
            saveErrors(request, errors);
            return displayUserUI(mapping, request);
        }
    }

    private ActionForward displayUserUI(ActionMapping mapping, HttpServletRequest request) {
        logger.info("authEngine is " + getAuthEngine().getClass().getName());
        request.setAttribute("isLoginRequired", getAuthEngine().isLoginRequired());
        request.setAttribute("isPasswordRequired", getAuthEngine().isPasswordRequired());
        return mapping.getInputForward();
    }

    private AuthEngine getAuthEngine() {
        return AuthEngine.Holder.getAuthEngine();
    }

    private ActionForward processSuccessfullAuthentification(ActionMapping mapping, HttpServletRequest request, XemeliosUser user) {
        AttributeHelper.setUser(request.getSession(), user);
        AttributeHelper.setMenu(request.getSession(), XemeliosHelper.getMenu(user));
        return mapping.findForward("success");
    }
}
