package com.kxs.common.mq.config;

import org.springframework.amqp.core.*;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

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


/**
 *   将spring容器的 [bean注册器]放置到属性中，为 RabbitConfig提供访问。
 *   顺序：
 *   1. postProcessBeanDefinitionRegistry (存放注册器)
 *   2. postProcessBeanFactory （没有使用）
 *   3. 注册延迟消息交换机的bean: delayedExchange
 *   4. 动态配置RabbitMQ所需的bean。
 *
 * @author 没秃顶的码农
 * @date 2024-04-25
 */
@Configuration
public class RabbitMQBeanProcessor implements BeanDefinitionRegistryPostProcessor {

    /** bean注册器 **/
    protected BeanDefinitionRegistry beanDefinitionRegistry;

    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry beanDefinitionRegistry) throws BeansException {
        this.beanDefinitionRegistry = beanDefinitionRegistry;
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
    }



    /**
     *  普通交换机
     */
    @Bean(name = RabbitConfiguration.EXCHANGE_TOPIC_RANCH)
    DirectExchange directExchange(){

        return new DirectExchange(RabbitConfiguration.EXCHANGE_TOPIC_RANCH,true,false);
    }

    /**
     *  死信交换机
     */
    @Bean(name = RabbitConfiguration.EXCHANGE_DEAD_RANCH)
    DirectExchange deadExchange(){

        return new DirectExchange(RabbitConfiguration.EXCHANGE_DEAD_RANCH,true,false);
    }

    /**
     * 广播交换机
     */
    @Bean(name = RabbitConfiguration.EXCHANGE_FANOUT_RANCH)
    FanoutExchange fanoutExchange(){
        return new FanoutExchange(RabbitConfiguration.EXCHANGE_FANOUT_RANCH, true, false);
    }

    /**
     * 延时交换机
     */
    @Bean(name = RabbitConfiguration.EXCHANGE_DELAY_RANCH)
    CustomExchange delayExchange(){
        Map<String, Object> args = new HashMap<>();
        args.put("x-delayed-type", "direct");
        return new CustomExchange(RabbitConfiguration.EXCHANGE_DELAY_RANCH,"x-delayed-message",true, false, args);
    }
}
