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.entity.resource.Server;
import com.bocloud.ims.interfaces.installation.HookService;
import com.bocloud.ims.repository.resource.ServerRepository;
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("rackhdTaskListener")
public class RackhdTaskListener implements MessageListener {
	private static final String TASK_FINISHED = "graph.finished.information.";
	private static Logger logger = LoggerFactory.getLogger(RackhdTaskListener.class);
	@Autowired
	private HookService hookService;
	@Autowired
	private ServerRepository serverRepository;

	@Override
	public void onMessage(Message message) {
		String routingKey = message.getMessageProperties().getReceivedRoutingKey();
		String content = new String(message.getBody(), StandardCharsets.UTF_8);
		logger.debug("get rackhd graph message \nroutingKey={} \nbody={}", routingKey, content);
		if (StringUtils.isBlank(content)) {
			// 消息没有内容，直接确认收到 淹没处理
			return;
		}
		JSONObject object = JSONTools.isJSONObj(content);
		if (null == object) {
			// 消息参数格式错误，直接确认收到淹没处理
			return;
		}
		// 任务节点通过instance判断是否是自己管理的机器，如果是，进行处理
		if (routingKey.startsWith(TASK_FINISHED)) {
			logger.info("get rackhd graph finished message \nroutingkey={} \nbody={}", routingKey, content);
			// 获取这个任务对应的物理机信息
			String nodeId = object.getString("nodeId");
			if (nodeId == null) {
				logger.error("rackhd graph finished message error!!! no nodeId");
				return;
			}
			Server server = serverRepository.getByNodeId(nodeId);
			if (server == null) {
				logger.error("nodeId为{}的物理机暂未被cmp管理，忽略此消息", nodeId);
				return;
			}

			BocloudResult result = hookService.task(object);
			if (result.isFailed()) {
				logger.error("处理机器任务失败:{}", result);
			}
		}
	}
}
