package com.elab.mq.rocket.template;

import com.elab.mq.rocket.utils.MsgConstants;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

/**
 * 消息发送模版拓展
 *
 * @author ： liukx
 * @time ： 2019/7/18 - 16:14
 */
public class DefaultMQProducerExt {

    private Logger logger = LoggerFactory.getLogger(DefaultMQProducerExt.class);

    private DefaultMQProducer defaultMQProducer;

    @Value("${spring.profiles.active:dev}")
    private String profiles;


    public DefaultMQProducerExt(DefaultMQProducer defaultMQProducer) {
        this.defaultMQProducer = defaultMQProducer;
    }

    public DefaultMQProducer getDefaultMQProducer() {
        return defaultMQProducer;
    }

    public SendResult send(String project, String tag, String key, byte[] body, int delayTimeLevel) throws InterruptedException, RemotingException, MQClientException, MQBrokerException {
        Message message = new Message();
        message.setBody(body);
        message.setTopic(getTopic(project));
        message.setTags(tag);
        message.setKeys(key);
        message.setDelayTimeLevel(delayTimeLevel);
        return defaultMQProducer.send(message);
    }

    public SendResult send(String project, String tag, String key, byte[] body) throws InterruptedException, RemotingException, MQClientException, MQBrokerException {
        return send(project, tag, key, body, 0);
    }

    public SendResult send(String project, String key, byte[] body) throws InterruptedException, RemotingException,
            MQClientException, MQBrokerException {
        return send(project, "*", key, body, 0);
    }

    public String getTopic(String project) {
        String topic = project + "-" + profiles + "-" + MsgConstants.TOPIC_SUFFIX;
        logger.info(" topic : " + topic);
        return topic;
    }

}
