package cn.lihongjie.coal.rabbitmq;

import org.apache.commons.collections4.MapUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

@Service
public class RabbitMQService {

    @Autowired RabbitTemplate rabbitTemplate;

    public void send(String exchange, String routingKey, Object data, Map<String, String> headers) {

        rabbitTemplate.convertAndSend(
                exchange,
                routingKey,
                data,
                message -> {
                    if (MapUtils.isNotEmpty(headers))
                        message.getMessageProperties().getHeaders().putAll(headers);
                    return message;
                });

    }

    public void sendToSysDelayExchange(String routingKey, Object data, long delay) {
        send(RabbitMQConfiguration.SYS_DELAY_EXCHANGE, routingKey, data, delay);
    }

    public void send(String exchange, String routingKey, Object data, long delay) {

        rabbitTemplate.convertAndSend(
                exchange,
                routingKey,
                data,
                message -> {
                    message.getMessageProperties()
                            .getHeaders()
                            .put("x-delay-queue-name", getBestDelayQueueName(delay));
                    return message;
                });
    }

    private String getBestDelayQueueName(long delay) {

        int length = RabbitMQConfiguration.DELAY_QUEUES_TIME.length;
        for (int i = 0; i < length; i++) {

            if (delay < (RabbitMQConfiguration.DELAY_QUEUES_TIME[i])) {
                return RabbitMQConfiguration.DELAY_QUEUES[i == 0 ? 0 : i - 1];
            }
        }
        
        throw new IllegalArgumentException("delay is too long: " + delay);
    }

    public void sendToSysExchange(String routingKey, Object data) {
        sendToSysExchange(routingKey, data, new HashMap<>());
    }

    public void sendToSysExchange(String routingKey, Object data, Map<String, String> headers) {
        send(RabbitMQConfiguration.SYS_EXCHANGE, routingKey, data, headers);
    }
}
