package com.braintree.security.handler;

import de.hybris.platform.cms2.model.site.CMSSiteModel;
import de.hybris.platform.cms2.servicelayer.services.CMSSiteService;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import static com.braintree.controllers.Braintreeb2baddonControllerConstants.PREPARATION_FOR_LINK_PAYPAL_ACCOUNT;
import static com.braintree.controllers.Braintreeb2baddonControllerConstants.PREPARATION_FOR_LINK_NO_AUTHENTICATION_PAYPAL_ACCOUNT;

public class BraintreeConnectWithPayPalSecurityLayerSuccessHandler implements AuthenticationSuccessHandler {

    private RedirectStrategy redirectStrategy;
    private CMSSiteService cmsSiteService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {

        final CMSSiteModel site = cmsSiteService.getCurrentSite();
        if (site.isRequiresAuthentication()) {
            redirectStrategy.sendRedirect(httpServletRequest, httpServletResponse, PREPARATION_FOR_LINK_PAYPAL_ACCOUNT);
        } else {
            redirectStrategy.sendRedirect(httpServletRequest, httpServletResponse, PREPARATION_FOR_LINK_NO_AUTHENTICATION_PAYPAL_ACCOUNT);
        }
    }

    public void setRedirectStrategy(RedirectStrategy redirectStrategy) {
        this.redirectStrategy = redirectStrategy;
    }

    public void setCmsSiteService(CMSSiteService cmsSiteService) {
        this.cmsSiteService = cmsSiteService;
    }
}
