package de.assecutor.votianlt.service;

import com.vaadin.flow.shared.Registration;
import de.assecutor.votianlt.event.MessageReadStatusChangedEvent;
import de.assecutor.votianlt.event.MessageReceivedEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Service;

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

/**
 * Service that listens for message-related events and notifies registered UI
 * components to update their message badges (e.g., in the sidebar navigation)
 */
@Service
@Slf4j
public class MessageBadgeUpdateService {

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

    /**
     * Register a listener that will be called when message badge should be updated
     * 
     * @param listener
     *            Runnable that will be called when badge update is needed
     * @return Registration object that can be used to unregister the listener
     */
    public synchronized Registration register(Runnable listener) {
        listeners.add(listener);
        log.debug("Registered badge update listener. Total listeners: {}", listeners.size());

        return () -> {
            synchronized (MessageBadgeUpdateService.this) {
                listeners.remove(listener);
                log.debug("Unregistered badge update listener. Total listeners: {}", listeners.size());
            }
        };
    }

    /**
     * Notify all registered listeners that badge should be updated
     */
    private synchronized void notifyListeners() {
        log.debug("Notifying {} badge update listeners", listeners.size());
        for (Runnable listener : listeners) {
            executor.execute(() -> {
                try {
                    listener.run();
                } catch (Exception e) {
                    log.error("Error notifying badge update listener", e);
                }
            });
        }
    }

    /**
     * Spring event listener for message read status changes
     */
    @EventListener
    public void onMessageReadStatusChanged(MessageReadStatusChangedEvent event) {
        log.debug("MessageBadgeUpdateService received MessageReadStatusChangedEvent");
        notifyListeners();
    }

    /**
     * Spring event listener for new messages received
     */
    @EventListener
    public void onMessageReceived(MessageReceivedEvent event) {
        log.debug("MessageBadgeUpdateService received MessageReceivedEvent");
        notifyListeners();
    }
}
