package cn.axzo.workflow.core.engine.listener;

import cn.axzo.workflow.core.common.context.ActivityOperationContext;
import cn.axzo.workflow.core.engine.event.BizCallbackEvent;
import cn.axzo.workflow.core.engine.event.BizCallbackEventImpl;
import cn.axzo.workflow.core.listener.BpmnActivityEventListener;
import com.google.common.collect.ImmutableSet;
import lombok.extern.slf4j.Slf4j;
import org.flowable.common.engine.api.delegate.event.AbstractFlowableEventListener;
import org.flowable.common.engine.api.delegate.event.FlowableEvent;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import static cn.axzo.workflow.core.engine.event.BizCallbackEventImpl.BizCallbackEventType.CALLBACK;

/**
 * 业务节点回调事件
 *
 * @author wangli
 * @since 2024-08-20 17:47
 */
@Slf4j
@Component
public class EngineActivityCallbackEventListener extends AbstractFlowableEventListener {
    @Resource
    ObjectProvider<List<BpmnActivityEventListener>> activityListeners;

    public static final Set<BizCallbackEventImpl.BizCallbackEventType> BIZ_CALLBACK_EVENTS =
            ImmutableSet.<BizCallbackEventImpl.BizCallbackEventType>builder()
                    .add(CALLBACK)
                    .build();

    @Override
    public void onEvent(FlowableEvent flowableEvent) {
        if (flowableEvent instanceof BizCallbackEvent) {
            BizCallbackEvent event = (BizCallbackEvent) flowableEvent;
            BizCallbackEventImpl.BizCallbackEventType type = (BizCallbackEventImpl.BizCallbackEventType) event.getType();
            if (BIZ_CALLBACK_EVENTS.contains(type)) {
                switch (type) {
                    case CALLBACK:
                        getOrderedListeners().forEach(i -> i.onCallback(event));
                        break;
                    default:
                }
            }
        }
    }

    private List<BpmnActivityEventListener> getOrderedListeners() {
        ActivityOperationContext context = new ActivityOperationContext();
        List<BpmnActivityEventListener> orderListeners = new ArrayList<>();
        activityListeners.ifAvailable(orderListeners::addAll);
        orderListeners.forEach(i -> i.setContext(context));
        return orderListeners;
    }

    @Override
    public boolean isFailOnException() {
        return true;
    }
}
