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

import com.braintree.customersupportbackoffice.actions.order.AbstractOrderAction;
import com.braintree.facade.backoffice.BraintreeBackofficeVoidFacade;
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 org.apache.log4j.Logger;

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

public class BraintreeVoidAction extends AbstractOrderAction {

    private static final Logger LOG = Logger.getLogger(BraintreeVoidAction.class);

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

    @Resource
    private BraintreeBackofficeVoidFacade braintreeBackofficeOrderFacade;

    @Resource
    private SessionService sessionService;

    @Override
    public String getConfirmationMessage(ActionContext<OrderModel> actionContext) {
        return "-abc-";
    }

    @Override
    public boolean needsConfirmation(ActionContext<OrderModel> actionContext) {
        return false;
    }

    @Override
    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 false;
                    }
                    return braintreeBackofficeOrderFacade.isVoidPossible(actionContext.getData());
                }
            });
        }
        return false;
    }

    @Override
    public ActionResult<OrderModel> perform(ActionContext<OrderModel> actionContext) {
        LOG.info("perform, actionContext: " + actionContext);

        sendOutput(SOCKET_OUT_CONTEXT, actionContext.getData());

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

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

}
