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

import com.braintree.customersupportbackoffice.actions.order.AbstractOrderAction;
import com.braintree.facade.backoffice.BraintreeBackofficeMultiCaptureFacade;
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.Map;

public class BrainTreeMultiCaptureAction extends AbstractOrderAction {

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

    @Resource
    private BraintreeBackofficeMultiCaptureFacade braintreeBackofficeMultiCaptureFacade;

    @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 braintreeBackofficeMultiCaptureFacade.isMultiCapturePossible(actionContext.getData());
                }
            });
        }
        return false;
    }

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

        return new ActionResult<>(ActionResult.SUCCESS);
    }

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

}
