package com.kxs.common.mq.handlers.rabbit;

import com.kxs.common.mq.config.RabbitConfiguration;
import com.kxs.common.mq.enums.MQSendTypeEnum;
import com.kxs.common.mq.handlers.IMQSender;
import com.kxs.common.mq.model.AbstractMQ;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

/**
 * rabbitMQ 消息发送器的实现
 *
 * @author 没秃顶的码农
 * @date 2024-04-25
 */
@Component
@RequiredArgsConstructor
public class RabbitMQSender implements IMQSender {

    private final RabbitTemplate rabbitTemplate;

    @Override
    public void send(AbstractMQ mqModel) {

        if(mqModel.getMqType() == MQSendTypeEnum.QUEUE){

            rabbitTemplate.convertAndSend(mqModel.getQueueName(), mqModel.toMessage());
        }
        if(mqModel.getMqType() == MQSendTypeEnum.FANOUT){

            rabbitTemplate.convertAndSend(RabbitConfiguration.EXCHANGE_FANOUT_RANCH + mqModel.getQueueName(), mqModel.getQueueName() + "_ROUTE", mqModel.toMessage());
        }

    }

    @Override
    public void send(AbstractMQ mqModel, int delay) {

        if(mqModel.getMqType() == MQSendTypeEnum.DELAY){

            rabbitTemplate.convertAndSend(RabbitConfiguration.EXCHANGE_DELAY_RANCH, mqModel.getQueueName(), mqModel.toMessage(), messagePostProcessor ->{
                messagePostProcessor.getMessageProperties().setDelay(Math.toIntExact(delay * 1000L));
                return messagePostProcessor;
            });
        }
    }

}
