package com.inspect.job.config;

import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.core.RabbitTemplate.ConfirmCallback;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RabbitConfig {
   @Value("${spring.rabbitmq.host}")
   private String addresses;
   @Value("${spring.rabbitmq.port}")
   private String port;
   @Value("${spring.rabbitmq.username}")
   private String username;
   @Value("${spring.rabbitmq.password}")
   private String password;
   @Value("${spring.rabbitmq.virtual-host}")
   private String virtualHost;
   @Value("${spring.rabbitmq.listener.montdata.exchange.name}")
   private String exchange;
   @Value("${spring.rabbitmq.listener.montdata.queue.name}")
   private String queue;
   @Value("${spring.rabbitmq.listener.montdata.key}")
   private String routingKey;

   @Bean
   public ConnectionFactory connectionFactory() {
      CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
      connectionFactory.setAddresses(this.addresses + ":" + this.port);
      connectionFactory.setUsername(this.username);
      connectionFactory.setPassword(this.password);
      connectionFactory.setVirtualHost(this.virtualHost);
      return connectionFactory;
   }

   @Bean
   public RabbitAdmin rabbitAdmin(ConnectionFactory connectionFactory) {
      return new RabbitAdmin(connectionFactory);
   }

   @Bean
   public RabbitTemplate newRabbitTemplate() {
      RabbitTemplate template = new RabbitTemplate(this.connectionFactory());
      template.setMandatory(true);
      template.setConfirmCallback(this.confirmCallback());
      return template;
   }

   public Queue AMessage() {
      return new Queue(this.queue);
   }

   @Bean
   public ConfirmCallback confirmCallback() {
      return new ConfirmCallback() {
         public void confirm(CorrelationData correlationData, boolean ack, String cause) {
            if(ack) {
               System.out.println("发送者确认发送给mq成功");
            } else {
               System.out.println("发送者发送给mq失败,考虑重发:" + cause);
            }

         }
      };
   }
}
