package cn.axzo.workflow.core.conf;

import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.stereotype.Component;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * Spring event 优雅关闭处理器
 *
 * @author wangli
 * @since 2025-04-07 17:10
 */
@Component
public class CustomEventManager implements ApplicationEventPublisherAware {

    private ApplicationEventPublisher publisher;
    private final BlockingQueue<ApplicationEvent> eventQueue = new LinkedBlockingQueue<>();
    private int eventCount = 0;

    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher publisher) {
        this.publisher = publisher;
    }

    public synchronized void publishEvent(ApplicationEvent event) {
        eventQueue.add(event);
        eventCount++;
        publisher.publishEvent(event);
    }

    public synchronized void eventProcessed() {
        eventQueue.poll();
        eventCount--;
    }

    public synchronized boolean isAllEventsProcessed() {
        return eventCount == 0;
    }

    public synchronized void waitForEventsToBeProcessed() throws InterruptedException {
        while (!isAllEventsProcessed()) {
            Thread.sleep(100);
        }
    }
}
