/**
 *
 */
package com.braintreeocc.filters;

import de.hybris.platform.commercewebservicescommons.strategies.CartLoaderStrategy;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class BraintreeCartMatchingFilter extends OncePerRequestFilter {

    private static final String CART_GUID = "cartGuid";
    public static final String REFRESH_CART_PARAM = "refreshCart";
    private CartLoaderStrategy cartLoaderStrategy;
    private boolean cartRefreshedByDefault = false;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        final String cartGuid = request.getParameter(CART_GUID);
        if (!StringUtils.isBlank(cartGuid)) {
            cartLoaderStrategy.loadCart(cartGuid, shouldCartBeRefreshed(request));
        }
        filterChain.doFilter(request, response);
    }

    protected boolean shouldCartBeRefreshed(final HttpServletRequest request) {
        final String refreshParam = request.getParameter(REFRESH_CART_PARAM);
        return refreshParam == null ? cartRefreshedByDefault : Boolean.parseBoolean(refreshParam);
    }

    @Required
    public void setCartLoaderStrategy(final CartLoaderStrategy cartLoaderStrategy) {
        this.cartLoaderStrategy = cartLoaderStrategy;
    }

    public void setCartRefreshedByDefault(final boolean cartRefreshedByDefault) {
        this.cartRefreshedByDefault = cartRefreshedByDefault;
    }
}
