package com.zsc.edu.gateway.framework.message.sse;

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Supplier;

/**
 * @author zhuang
 */
@Component
public class SseConfig {
    private final ExecutorService executorService = Executors.newCachedThreadPool();

    public SseEmitter sendSseEvents(Supplier<Object> dataSupplier) {
        SseEmitter emitter = new SseEmitter(30000L);

        AtomicBoolean isCompleted = new AtomicBoolean(false);
        emitter.onCompletion(() -> isCompleted.set(true));

        executorService.execute(() -> {
            try {
                while (!isCompleted.get()) {
                    Object data = dataSupplier.get();
                    if (data == null) {
                        break;
                    }
                    if (!isCompleted.get()) {
                        emitter.send(SseEmitter.event().data(data));
                    }
                    Thread.sleep(5000);
                }
            } catch (IOException | InterruptedException e) {
                emitter.completeWithError(e);
            } finally {
                emitter.complete();
            }
        });
        return emitter;
    }


}
