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

import cn.axzo.workflow.core.engine.event.ErrorInfoEvent;
import cn.axzo.workflow.core.engine.event.ErrorInfoEventType;
import cn.axzo.workflow.core.listener.BpmnAsyncExecutionErrorEventListener;
import com.google.common.collect.ImmutableSet;
import lombok.extern.slf4j.Slf4j;
import org.flowable.common.engine.api.delegate.event.FlowableEvent;
import org.flowable.engine.delegate.event.AbstractFlowableEngineEventListener;
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.ErrorInfoEventType.NEW_ERROR;

/**
 * TODO
 *
 * @author wangli
 * @since 2024/4/17 16:52
 */
@Slf4j
@Component
public class EngineAsyncExecutionErrorEventListener extends AbstractFlowableEngineEventListener {

    @Resource
    ObjectProvider<List<BpmnAsyncExecutionErrorEventListener>> errorEventListeners;

    public static final Set<ErrorInfoEventType> ACCEPT_EVENTS =
            ImmutableSet.<ErrorInfoEventType>builder()
                    .add(NEW_ERROR)
                    .build();

    @Override
    public void onEvent(FlowableEvent flowableEvent) {
        if (flowableEvent instanceof ErrorInfoEvent) {
            ErrorInfoEvent event = (ErrorInfoEvent) flowableEvent;
            ErrorInfoEventType eventType = (ErrorInfoEventType) flowableEvent.getType();

            if (ACCEPT_EVENTS.contains(eventType)) {
                switch (eventType) {
                    case NEW_ERROR:
                        getOrderedListeners().forEach(i -> i.notify(event.getJob(), event.getThrowable()));
                        break;
                    default:
                        break;
                }
            }
        }
    }

    private List<BpmnAsyncExecutionErrorEventListener> getOrderedListeners() {
        List<BpmnAsyncExecutionErrorEventListener> orderListeners = new ArrayList<>();
        errorEventListeners.ifAvailable(orderListeners::addAll);
        return orderListeners;
    }

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

}
