package com.bocloud.ims.booter.listener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.bocloud.cmp.entity.enums.ResourceCategory;
import com.bocloud.cmp.model.common.AlterationParam;
import com.bocloud.cmp.model.common.OrderMessage;
import com.bocloud.ims.interfaces.apply.ResourceOperationService;

/**
 * 资源变更监听器
 * 
 * @author wangyu
 * @version 1.0
 * @since 2020年4月16日
 *
 */
@Component
public class ResourceChangeListener {

	private static Logger logger = LoggerFactory.getLogger(ResourceChangeListener.class);
	@Autowired
	private ResourceOperationService resourceOperationService;
	private static final String MODIFICATION_QUEUE = "iaas.resource.modification.queue";

	@RabbitListener(queues = MODIFICATION_QUEUE, admin = "amqpAdmin", autoStartup = "true")
	public void process(AlterationParam param) throws Exception {
		try {
			if (null == param) {
				return;
			}
			logger.info("接收到资源变更消息：{}", JSONObject.toJSONString(param));
			String category = param.getCategory();
			OrderMessage.Operation operation = OrderMessage.Operation.Upgrade;
			if (AlterationParam.Operation.ScaleIn == param.getOperation()) {
				operation = OrderMessage.Operation.ScaleIn;
			} else if (AlterationParam.Operation.ScaleOut == param.getOperation()) {
				operation = OrderMessage.Operation.ScaleOut;
			}
			resourceOperationService.process(ResourceCategory.valueOf(category),
					JSONObject.parseObject(JSONObject.toJSONString(param)), operation);
		} catch (Exception e) {
			logger.error("Get error message:{}", e.getMessage());
		}
	}

}
