package com.braintree.controllers.handler;

import com.braintree.enums.ExpirationStatus;
import com.braintree.facade.impl.DefaultBrainTreePaymentFacade;
import de.hybris.platform.addonsupport.interceptors.BeforeViewHandlerAdaptee;
import de.hybris.platform.servicelayer.user.UserService;
import org.springframework.http.HttpHeaders;
import org.springframework.ui.ModelMap;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import de.hybris.platform.acceleratorstorefrontcommons.controllers.util.GlobalMessages;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class BrainTreeBeforeNotificationViewHandler implements BeforeViewHandlerAdaptee {

    private static final String EXPIRED_MESSAGE = "braintree.paypal.payment.notification.expired";
    private static final String EXPIRED_SOON_MESSAGE = "braintree.paypal.payment.notification.expired.soon";

    private static final String LOGIN_PAGE_REGEX = "(/login(/checkout)?)";

    @Resource(name = "userService")
    private UserService userService;

    @Resource(name = "brainTreePaymentFacadeImpl")
    private DefaultBrainTreePaymentFacade brainTreePaymentFacade;

    @Override
    public String beforeView(HttpServletRequest request, HttpServletResponse response, ModelMap model, String viewName) throws Exception {
        String referer = request.getHeader(HttpHeaders.REFERER);
        String previousView = referer != null ? referer : "";
        Matcher matcher = Pattern.compile(LOGIN_PAGE_REGEX).matcher(previousView);
        if (!userService.isAnonymousUser(userService.getCurrentUser())
                && matcher.find()) {
            String expiredStatus = brainTreePaymentFacade.getExpirationStatusForCustomer();
            if (expiredStatus.equals(ExpirationStatus.EXPIRED.getCode())) {
                GlobalMessages.addFlashMessage(model, GlobalMessages.INFO_MESSAGES_HOLDER,
                        EXPIRED_MESSAGE, null);
            }
            if (expiredStatus.equals(ExpirationStatus.EXPIRE_SOON.getCode())) {
                GlobalMessages.addFlashMessage(model, GlobalMessages.INFO_MESSAGES_HOLDER,
                        EXPIRED_SOON_MESSAGE, null);
            }
        }
        return viewName;
    }
}
