package com.braintree.interceptors;

import com.braintree.configuration.service.BrainTreeConfigService;
import de.hybris.platform.basecommerce.model.site.BaseSiteModel;
import de.hybris.platform.core.model.BraintreeGeneralConfigurationModel;
import de.hybris.platform.core.model.BraintreePluginConfigurationModel;
import de.hybris.platform.servicelayer.interceptor.InterceptorContext;
import de.hybris.platform.servicelayer.interceptor.PrepareInterceptor;
import de.hybris.platform.servicelayer.model.ModelService;
import de.hybris.platform.servicelayer.session.SessionExecutionBody;
import de.hybris.platform.servicelayer.session.SessionService;

import java.util.Map;
import java.util.Optional;

import static com.braintree.constants.BraintreeConstants.CURRENT_SITE;
import static com.braintree.constants.BraintreeConstants.MIN_PAYPAL_BTN_HEIGHT;
import static com.braintree.constants.BraintreeConstants.MIN_PAYPAL_DROP_IN_BTN_HEIGHT;

public class BraintreeBraintreeGeneralConfigurationSaveInterceptor implements
        PrepareInterceptor<BraintreeGeneralConfigurationModel> {

    private BrainTreeConfigService brainTreeConfigService;

    private SessionService sessionService;

    private ModelService modelService;

    @Override
    public void onPrepare(BraintreeGeneralConfigurationModel braintreeGeneralConfigurationModel,
                          InterceptorContext interceptorContext) {
        if (braintreeGeneralConfigurationModel.isDropIn()) {
            Optional<BaseSiteModel> baseSite = brainTreeConfigService.getBaseSiteForGeneralConfigurationId(braintreeGeneralConfigurationModel.getBraintreeGeneralConfigurationId());
            if (baseSite.isPresent()) {
                BraintreePluginConfigurationModel pluginConfigurationModel = sessionService.executeInLocalViewWithParams(
                        Map.of(CURRENT_SITE, baseSite.get()), new SessionExecutionBody() {
                            @Override
                            public Object execute() {
                                return brainTreeConfigService.getBrainTreePluginConfiguration();
                            }
                        });
                pluginConfigurationModel.getBraintreePayPalConfiguration().getBraintreePayPalStylesConfiguration().stream()
                        .filter(style -> style.getHeight() < MIN_PAYPAL_DROP_IN_BTN_HEIGHT)
                        .forEach(style -> {
                            style.setHeight(MIN_PAYPAL_DROP_IN_BTN_HEIGHT);
                            modelService.save(style);
                        });
            }
        }
    }

    public void setBrainTreeConfigService(BrainTreeConfigService brainTreeConfigService) {
        this.brainTreeConfigService = brainTreeConfigService;
    }

    public void setSessionService(SessionService sessionService) {
        this.sessionService = sessionService;
    }

    public void setModelService(ModelService modelService) {
        this.modelService = modelService;
    }

}
