package com.iformall.mq.impl;

import com.iformall.mq.AmqpMsgConsumer;
import com.iformall.mq.MQConfig;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component
@Profile(MQConfig.Impl.RABBIT_MQ)
public class RabbitMqAmqpMsgConsumer extends AmqpMsgConsumer {
    String queueName = "topic-amqp";

    @Autowired
    private AmqpAdmin amqpAdmin;

    @PostConstruct
    public void init() {
        DirectExchange exchange = new DirectExchange(queueName);
        Queue queue = new Queue(queueName);
        Binding binding = BindingBuilder.bind(queue).to(exchange).withQueueName();
        amqpAdmin.declareExchange(exchange);
        amqpAdmin.declareQueue(queue);
        amqpAdmin.declareBinding(binding);
    }

    @Autowired
    private AmqpTemplate rabbitTemplate;

    public void send(String msg) {
        rabbitTemplate.convertAndSend(queueName, msg);
    }

    @RabbitListener(queues = "topic-amqp")
    public void onMessage(String message) {
        doMessage(message);
    }
}
