package com.bocloud.ims.service.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.bocloud.common.enums.BoCloudExchange;
import com.bocloud.common.model.OperateResult;
import com.bocloud.common.model.Result;

/**
 * 资源事件结果分发器，用来将异步操作的结果发送到RabbitMQ里面去。
 *
 * @author dmw
 */
@Component("resourceEventPublisher")
public class ResourceEventPublisher {
    private static Logger logger = LoggerFactory.getLogger(ResourceEventPublisher.class);
    @Autowired
    private AmqpTemplate amqpTemplate;
    private static String EXCHANGE = BoCloudExchange.Default.TOPIC.getExchange();
    private static String ROUITING = "bocloud.message.queue.#";

    public Result send(Object message) {
        try {
            if (message instanceof OperateResult) {
                OperateResult result = (OperateResult) message;
                result.setOperate(null == result.getOperate() ? "" : result.getOperate());
                message = result;
            }
            this.amqpTemplate.convertAndSend(EXCHANGE, ROUITING, message);
            return new Result(true, "success");
        } catch (AmqpException e) {
            logger.error("Send Resource Event Error{}", e);
            return new Result(false, "发送失败！");
        }
    }
}
