package de.assecutor.votianlt.service;

import com.vaadin.flow.shared.Registration;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.stereotype.Service;

import java.util.LinkedHashSet;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.function.Consumer;

@Service
@Slf4j
public class JobUpdateBroadcaster {

    private final Executor executor = Executors.newSingleThreadExecutor();
    private final LinkedHashSet<Consumer<ObjectId>> listeners = new LinkedHashSet<>();

    public synchronized Registration register(Consumer<ObjectId> listener) {
        listeners.add(listener);
        return () -> {
            synchronized (JobUpdateBroadcaster.this) {
                listeners.remove(listener);
            }
        };
    }

    public synchronized void broadcast(ObjectId jobId) {
        if (jobId == null) {
            return;
        }

        for (Consumer<ObjectId> listener : listeners) {
            executor.execute(() -> {
                try {
                    listener.accept(jobId);
                } catch (Exception e) {
                    log.error("Error broadcasting job update for {}", jobId.toHexString(), e);
                }
            });
        }
    }
}
