package com.braintree.customersupportbackoffice.actions.order.adjustauthorization;

import com.braintree.customersupportbackoffice.actions.order.AbstractOrderAction;
import com.braintree.facade.backoffice.BraintreeBackofficeAdjustAuthorizationFacade;
import com.braintree.model.BrainTreePaymentInfoModel;
import com.hybris.cockpitng.actions.ActionContext;
import com.hybris.cockpitng.actions.ActionResult;
import de.hybris.platform.core.model.order.OrderModel;
import de.hybris.platform.servicelayer.session.SessionExecutionBody;
import de.hybris.platform.servicelayer.session.SessionService;

import javax.annotation.Resource;
import java.util.EnumSet;
import java.util.Map;

public class BrainTreeAdjustAuthorizationAction extends AbstractOrderAction {

    protected static final String SOCKET_OUT_CONTEXT = "adjustAuthorizationContext";
    private static final String CURRENT_SITE = "currentSite";

    @Resource
    private BraintreeBackofficeAdjustAuthorizationFacade braintreeBackofficeAdjustAuthorizationFacade;

    @Resource
    private SessionService sessionService;

    public boolean canPerform(ActionContext<OrderModel> actionContext) {
        if (actionContext.getData() != null) {
            return sessionService.executeInLocalViewWithParams(Map.of(CURRENT_SITE, actionContext.getData().getSite()), new SessionExecutionBody() {
                @Override
                public Object execute() {
                    if (!isExtendedPaymentInfo(actionContext)) {
                        actionContext.setParameter(ActionContext.VIEW_MODE_PARAM, ActionContext.VIEWMODE_HIDDEN);
                    }
                    return braintreeBackofficeAdjustAuthorizationFacade.isAdjustAuthorizationPossible(actionContext.getData());
                }
            });
        }
        return false;
    }

    public ActionResult<OrderModel> perform(ActionContext<OrderModel> actionContext) {
        sendOutput(SOCKET_OUT_CONTEXT, actionContext.getData());

        ActionResult<OrderModel> actionResult = new ActionResult<>(ActionResult.SUCCESS);
        actionResult.setStatusFlags(EnumSet.of(ActionResult.StatusFlag.OBJECT_MODIFIED));
        return actionResult;
    }

    private boolean isExtendedPaymentInfo(ActionContext<OrderModel> actionContext) {
        return actionContext.getData().getPaymentInfo() instanceof BrainTreePaymentInfoModel;
    }

}
