/* ======================================================================
   Parts Copyright 2006 University of Leeds, Oxford University, University of the Highlands and Islands.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

====================================================================== */

package org.bodington.servlet;

import java.util.Properties;

import javax.servlet.http.Cookie;

import org.apache.log4j.Logger;
import org.bodington.server.BuildingContext;
import org.bodington.server.BuildingServerException;
import org.bodington.server.NavigationSession;

/**
 * Abstract implementation of a session initializer. This class is intended
 * to assist in the implementation of concrete subclasses by capturing
 * commonality. 
 * Uses the property buildingservlet.session.timeout to set the default session 
 * timeout in minutes.
 * @author Alexis O'Connor
 */
public abstract class AbstractSessionInitializer implements SessionInitializer
{
    private static Logger log = Logger.getLogger(AbstractSessionInitializer.class);
    
    private SessionInitializer next;
    
    /**
     * Pass the request to the next link in the chain. This method is used to
     * simply exit control from this object by calling the
     * {@link #handleRequest(Request)} method of the next link in the
     * chain. If there is no subsequent link, this method returns
     * <code>null</code>.
     * @param request the request object.
     * @return the result of the subsequent link's
     *         {@link #handleRequest(Request)} method, or
     *         <code>null</code> if this is the last link in the chain.
     * @see #handleRequest(Request)
     */
    protected NavigationSession passToNextLink( Request request )
    {
        return (next != null) ? next.handleRequest(request) : null;
    }

    public void setNextSessionInitializer( SessionInitializer initializer )
    {
        next = initializer;
    }
    
    /**
     * Find a session associated with the request. If no session can be
     * found, this method returns <code>null</code>. If this method returns
     * <code>null</code>, then code elsewhere assumes that the instance should
     * pass the request to the next link in the chain. This implementation of
     * the method attempts to find the session by looking for an associated
     * cookie.
     * @param request the request to be examined.
     * @return a session associated with the request.
     * @see Cookie
     */
    protected HttpSession findHttpSession( Request request )
    {
        Cookie[] cookies = request.getCookies();
        if ( cookies == null ) 
            return null;
        for ( int i = 0; i < cookies.length; i++ )
        {
            if ( Request.SESSION_ID_COOKIE_NAME.equals( cookies[i].getName() ) )
            {
                HttpSession session 
                    = HttpSession.findSessionById( cookies[i].getValue() );
                if ( session != null ) 
                    return session;
                else
                    log.debug("Failed to find session. Cookie Value: "+ cookies[i].getValue());
            }
        }
        
        return null;
    }
    
    /**
     * Setup the navigation session so authentication can be attempted.
     * This method is intended to be overridden by subclasses to perform 
     * the work of setting up the credentials in the navigation session 
     * specific to their enclosing class.
     * @param request the current request.
     * @param session the associated session instance.
     * @param navigation the navigation session to be authenticated.
     * @return <code>true</code> if authentication information was found
     * and was set in the session.
     * @see NavigationSession#setAuthenticationCredentials(Properties, String)
     */
    protected abstract boolean initialize(
        Request request, HttpSession session, NavigationSession navigation );

    /**
     * Post initialize the session. This method is guaranteed to only ever be
     * called on a session whose associated {@link NavigationSession} instance
     * has been successfully authenticated. The default implementation
     * sets the session timeout and clears out the session a little.
     * @param session the session object to be post initialized.
     * @param request the request which has been authenticated.
     * @see NavigationSession
     * @see NavigationSession#isAuthenticated()
     */
    protected void postInitialize( HttpSession session, Request request )
    {
        NavigationSession navigation = session.getServerNavigationSession();

        try
        {
            int time = BuildingContext.getProperty("buildingservlet.session.timeout", 120, false);
            session.setMaxInactiveInterval(time * 60); // API likes seconds.
            
            if (navigation.getAuthenticatedUser().isValid())
            {
                session.cleanout();
            }
            else
            {
                // TODO Should set some message about account being invalid
                navigation.clearAuthenticationCredentials();
            }
        }
        catch ( BuildingServerException e )
        {
            log.warn("Problem finishing setting up session.", e);
        }
    }

    public NavigationSession handleRequest( Request request )
    {
        HttpSession session = findHttpSession( request );
        if (session == null)
            return passToNextLink( request );
        
        // Bind the session to the request.
        request.setAttribute( Request.SESSION_ATTRIBUTE_NAME, session );
        
        NavigationSession navigation = session.getServerNavigationSession();
        
        try
        {
            if (initialize(request, session, navigation ) && navigation.isAuthenticated())
            {
                postInitialize( session, request );
                return navigation;
            }
        }
        catch ( BuildingServerException e )
        {
            log.warn("Problem cheching if user is authenticated.", e);
        }
        return passToNextLink( request ); // default behaviour.
    }
}
