package com.jpsoft.shinestar.modules.mq.manager;

import com.jpsoft.shinestar.modules.mq.listener.DeviceMessageListener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.amqp.rabbit.listener.adapter.MessageListenerAdapter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
public class QueueManager {
    @Autowired
    private AmqpAdmin amqpAdmin;

    @Autowired
    private DirectExchange deviceExchange;

    @Autowired
    private ConnectionFactory connectionFactory;

    @Autowired
    private DeviceMessageListener deviceMessageListener;

    private Map<String, SimpleMessageListenerContainer> simpleMessageListenerContainerMap = new HashMap<>();

    public void createQueue(String queueName){
        try {
            Queue queue = new Queue(queueName);
            String result = amqpAdmin.declareQueue(queue);

            log.warn("创建队列：" + queueName + ",result=" + result);

            Binding binding = BindingBuilder.bind(queue).to(deviceExchange).with(queueName);
            amqpAdmin.declareBinding(binding);

            SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
            container.setConnectionFactory(connectionFactory);

            MessageListenerAdapter messageListenerAdapter = new MessageListenerAdapter(deviceMessageListener);
            container.setConcurrentConsumers(1);
            container.setMessageListener(messageListenerAdapter);

            //队列订阅事件
            container.addQueueNames(queueName);

            simpleMessageListenerContainerMap.put(queueName, container);

            //开始监听事件
            container.start();
        }
        catch (Exception ex){
            log.error("创建队列失败!" + ex.getMessage());
        }
    }

    public void stopListen(String queueName){
        if (simpleMessageListenerContainerMap.containsKey(queueName)){
            SimpleMessageListenerContainer container = simpleMessageListenerContainerMap.get(queueName);

            if (container!=null && container.isRunning()){
                container.stop();
            }
        }
    }
}
