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

import cn.axzo.workflow.core.common.context.ActivityOperationContext;
import cn.axzo.workflow.core.listener.BpmnActivityEventListener;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.ExecutionListener;
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.Objects;

/**
 * 活动节点结束事件监听器
 *
 * @author wangli
 * @since 2023/12/21 16:55
 */
@Component
@Slf4j
public class EngineActivityEndEventListener implements ExecutionListener {
    private static final String EVENT_NAME = "activityEnd:";
    @Resource
    ObjectProvider<List<BpmnActivityEventListener>> activityListeners;

    @Override
    public void notify(DelegateExecution execution) {
        if (Objects.nonNull(execution.getTransientVariable(EVENT_NAME + execution.getCurrentActivityId()))) {
            return;
        }
        log.info("EngineActivityEndEventListener Event: {}, ActivityId: {}", execution.getEventName(),
                execution.getCurrentActivityId());
        getOrderedListeners().forEach(i -> i.onEnd(execution));
        execution.setTransientVariable(EVENT_NAME + execution.getCurrentActivityId(), true);
    }

    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;
    }
}
