package com.bocloud.ims.booter.listener;

import com.alibaba.fastjson.JSONObject;
import com.bocloud.common.model.BocloudResult;
import com.bocloud.common.model.RequestContext;
import com.bocloud.common.utils.JSONTools;
import com.bocloud.ims.interfaces.installation.HookService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.nio.charset.StandardCharsets;

/**
 * RackHD发现消息监听器
 *
 * @author lkx007
 * <p>
 * specfication
 * <p>
 * https://rackhd.readthedocs.io/en/latest/rackhd_api/northbound_event_notification.html#event-payload
 */
@Repository("rackhdDiscoverListener")
public class RackhdDiscoverListener implements MessageListener {
    private static final String DISCOVER = "node.discovered.information.";
    private static Logger logger = LoggerFactory.getLogger(RackhdDiscoverListener.class);
    @Autowired
    private HookService hookService;

    @Override
    public void onMessage(Message message) {
        String routingKey = message.getMessageProperties().getReceivedRoutingKey();
        String content = new String(message.getBody(), StandardCharsets.UTF_8);
        logger.info("get rackhd discover message \nroutingKey={} \nbody={}", routingKey, content);
        if (StringUtils.isBlank(content)) {
            // 消息没有内容，直接确认收到 淹没处理
            return;
        }
        JSONObject object = JSONTools.isJSONObj(content);
        if (null == object) {
            // 消息参数格式错误，直接确认收到淹没处理
            return;
        }
        if (routingKey.startsWith(DISCOVER)) {
            BocloudResult result = hookService.discover(object);
            if (result.isFailed()) {
                logger.error("处理机器发现失败:{}", result);
            }
        }
    }

}
