/**
 * Copyright (c) 2006 Red Hat, Inc. All rights reserved.
 *
 * This library 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 2.1 of the License, or any later version.
 *
 * This library 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 this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA
 *
 * Component of: Red Hat Application Server
 * 
 * Initial Developers: Greg Lapouchnian
 *                     Patrick Smith
 *
 */

package olstore.controller;

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

import olstore.domain.logic.OlstoreFacade;
import olstore.domain.manager.CartManager;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

/**
 * An interceptor class used to ensure a cart object is attached to the session.
 */
public class ShoppingCartInterceptor extends HandlerInterceptorAdapter {

    // The olstore bean instance that is provided via Spring.
    private OlstoreFacade olstore;

    /**
     * The Spring injection setter method for the olstore bean instance.
     * @param olstore the bean instance that is provided via spring.
     */
    public void setOlstore(OlstoreFacade olstore) {
        this.olstore = olstore;
    }

    /**
     * A method that is invoked before passing control on.
     *
     * @param request the HttpServletRequest.
     * @param response the HttpServletResponse.
     * @param handler the handler object being used.
     */
    public boolean preHandle(
            HttpServletRequest request,
            HttpServletResponse response,
            Object handler)
    throws Exception {
        HttpSession session = request.getSession(true);
        
        if(request.getRemoteUser()!=null || request.getUserPrincipal()!=null) {
            if(session.getAttribute("cart") == null) {
                CartManager cart = olstore.getShoppingCart(request.getRemoteUser());
                session.setAttribute("cart", cart);
            }
        }
        return true;
    }
}
