package com.qqchen.deploy.backend.workflow.event;

import com.qqchen.deploy.backend.workflow.event.handler.IFlowableEventHandler;
import lombok.extern.slf4j.Slf4j;
import org.flowable.common.engine.api.delegate.event.FlowableEvent;
import org.flowable.common.engine.api.delegate.event.FlowableEventListener;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import jakarta.annotation.Resource;

import java.util.List;

@Slf4j
@Component
public class FlowableEventDispatcher implements FlowableEventListener {

    @Resource
    @Lazy
    private List<IFlowableEventHandler> eventHandlers;

    @Override
    public void onEvent(FlowableEvent event) {
        String eventType = event.getType().name();
        log.info("Dispatching Flowable event: {}, event class: {}", eventType, event.getClass().getName());
        for (IFlowableEventHandler handler : eventHandlers) {
            if (handler.canHandle(eventType)) {
                try {
                    handler.handle(event);
                } catch (Exception e) {
                    log.error("Error handling event {} by handler {}: {}", eventType, handler.getClass().getSimpleName(), e.getMessage(), e);
                }
            }
        }
    }

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

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

    @Override
    public String getOnTransaction() {
        return "committed";
    }
}