package com.eactive.testmaster.queue.service;

import com.eactive.testmaster.config.HazelcastJSBridge;
import com.eactive.testmaster.queue.entity.QueueHandler;
import com.hazelcast.core.HazelcastInstance;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class DynamicQueueManager {

    private static final Logger logger = LoggerFactory.getLogger(DynamicQueueManager.class);

    private final HazelcastInstance hazelcastInstance;
    private final Map<String, QueueListenerService> queueListeners;
    private final HazelcastJSBridge hazelcastJSBridge;

    @Autowired
    public DynamicQueueManager(HazelcastInstance hazelcastInstance, HazelcastJSBridge hazelcastJSBridge) {
        this.hazelcastInstance = hazelcastInstance;
        this.hazelcastJSBridge = hazelcastJSBridge;
        this.queueListeners = new ConcurrentHashMap<>();
    }

    /**
     * Start a listener for the specified queue
     */
    public void startQueueListener(QueueHandler queueHandler) {
        QueueListenerService existingListener = queueListeners.get(queueHandler.getQueueName());
        if (existingListener != null) {
            // If exists but not running, remove it so we can start fresh
            if (!existingListener.isRunning()) {
                queueListeners.remove(queueHandler.getQueueName());
            } else {
                logger.warn("Listener already exists and running for queue: {}", queueHandler.getQueueName());
                return;
            }
        }

        QueueListenerService listener = new QueueListenerService(hazelcastInstance, hazelcastJSBridge);
        listener.setQueueHandler(queueHandler);
        queueListeners.put(queueHandler.getQueueName(), listener);
        listener.startListening();
        logger.info("Started listener for queue: {}", queueHandler.getQueueName());
    }

    /**
     * Stop a queue listener
     */
    public void stopQueueListener(String queueName) {
        QueueListenerService listener = queueListeners.remove(queueName);
        if (listener != null) {
            listener.stopListening();
            logger.info("Stopped listener for queue: {}", queueName);
        }
    }

}
