package com.yihu.hos.services;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.hos.common.constants.ContextAttributes;
import com.yihu.hos.core.log.Logger;
import com.yihu.hos.core.log.LoggerFactory;
import com.yihu.hos.interceptor.LocalContext;
import com.yihu.hos.web.framework.constant.SSHConstant;
import com.yihu.hos.web.framework.model.bo.ServiceShell;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.zbus.broker.ZbusBroker;
import org.zbus.mq.Producer;
import org.zbus.net.http.Message;

import java.io.IOException;

/**
 * 发送shell命令消息到ＭＱ
 *
 * @author HZY
 * @vsrsion 1.0
 * Created at 2017/1/5.
 */
@Component
public class ServiceShellEventService {
    static final Logger logger = LoggerFactory.getLogger(ServiceShellEventService.class);

    @Autowired
    private ObjectMapper objectMapper;

    private ZbusBroker zbusBroker;

    @Autowired
    public void setZbusBroker(ZbusBroker zbusBroker) {
        this.zbusBroker = zbusBroker;
    }

    public void serviceShellSend(ServiceShell serviceShell) {
        serviceShell.setType(SSHConstant.ARBITER_SHELL_SEND);
        this.sendMsg(SSHConstant.ARBITER_SHELL_SEND, serviceShell);
    }


    private void sendMsg(String event, ServiceShell serviceShell) {
        if (zbusBroker == null) {
            logger.error("zbusBroker is null.");
            return;
        }

        try {
            String msg = objectMapper.writeValueAsString(serviceShell);
            String tenant = LocalContext.getContext().getAttachment(ContextAttributes.TENANT_NAME);

            Producer producer = new Producer(zbusBroker, SSHConstant.SHELL_REQUEST + "@" + tenant);
            producer.createMQ();    //确定为创建消息队列需要显示调用
            Message message = new Message();
            message.setHead("event", event);
            message.setHead("tenant", tenant);
            message.setMethod("POST");
            message.setBody(msg);
            producer.sendSync(message);
        } catch (IOException | InterruptedException e) {
            logger.error(e.getMessage());
            e.printStackTrace();
        }
    }


}
