package com.sino.mci.channel.messaging;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 企微会话存档拉取任务 RabbitMQ 配置。
 */
@Configuration
public class RabbitConfig {

    public static final String SESSION_ARCHIVE_QUEUE = "mci.wecom.session_archive.pull";
    public static final String SESSION_ARCHIVE_EXCHANGE = "mci.wecom";
    public static final String SESSION_ARCHIVE_ROUTING_KEY = "session_archive.pull";

    @Bean
    public Queue sessionArchiveQueue() {
        return new Queue(SESSION_ARCHIVE_QUEUE, true);
    }

    @Bean
    public TopicExchange sessionArchiveExchange() {
        return new TopicExchange(SESSION_ARCHIVE_EXCHANGE, true, false);
    }

    @Bean
    public Binding sessionArchiveBinding(Queue sessionArchiveQueue, TopicExchange sessionArchiveExchange) {
        return BindingBuilder.bind(sessionArchiveQueue).to(sessionArchiveExchange).with(SESSION_ARCHIVE_ROUTING_KEY);
    }

    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate template = new RabbitTemplate(connectionFactory);
        template.setMessageConverter(new Jackson2JsonMessageConverter());
        return template;
    }

    @Bean
    public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory(ConnectionFactory connectionFactory) {
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        factory.setConnectionFactory(connectionFactory);
        Jackson2JsonMessageConverter converter = new Jackson2JsonMessageConverter(
                "com.sino.mci.*", "java.util", "java.lang");
        factory.setMessageConverter(converter);
        return factory;
    }
}
