package com.yihu.hos.services;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.hos.core.log.Logger;
import com.yihu.hos.core.log.LoggerFactory;
import com.yihu.hos.web.framework.constant.MycatConstant;
import com.yihu.hos.web.framework.model.bo.ServiceMycat;
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;

/**
 * mycat配置文件操作 消息到ＭＱ
 *
 * @author HZY
 * @vsrsion 1.0
 * Created at 2017/1/5.
 */
@Component
public class ServiceMycatEventService {
    static final Logger logger = LoggerFactory.getLogger(ServiceMycatEventService.class);

    @Autowired
    private ObjectMapper objectMapper;
    private ZbusBroker zbusBroker;

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

    public void executeMycatConfig(ServiceMycat servviceMycat, String tenantAndHost) {
        this.sendMsg(MycatConstant.EXECUTE_MYCAT, servviceMycat, tenantAndHost);
    }


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

        try {
            String msg = objectMapper.writeValueAsString(servviceMycat);

            Producer producer = new Producer(zbusBroker, MycatConstant.ZBUS_MQ + "@" + tenantAndHost);
            producer.createMQ();    //确定为创建消息队列需要显示调用
            Message message = new Message();
            message.setHead("event", event);
            message.setHead("tenant", tenantAndHost);
            message.setMethod("POST");
            message.setBody(msg);
            producer.sendSync(message);

        } catch (JsonProcessingException e) {
            e.printStackTrace();
            logger.error(e.getMessage());
        } catch (InterruptedException | IOException e) {
            e.printStackTrace();
        }
    }


}
