package com.bocloud.ims.booter.listener;

import com.alibaba.fastjson.JSONObject;
import com.bocloud.cmp.entity.enums.ResourceCategory;
import com.bocloud.cmp.model.common.ApplicationParam;
import com.bocloud.cmp.model.common.OrderMessage;
import com.bocloud.common.model.Result;
import com.bocloud.common.utils.JSONTools;
import com.bocloud.common.utils.ListTool;
import com.bocloud.ims.interfaces.apply.ResourceOperationService;
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 java.util.List;

/**
 * 资源申请监听器
 *
 * @author wangyu
 * @version 1.0
 * @since 2018年1月8日
 */
@Component
public class ResourceApplyListener {

    private static Logger logger = LoggerFactory.getLogger(ResourceApplyListener.class);
    @Autowired
    private ResourceOperationService resourceOperationService;
    private static final String CREATION_QUEUE = "iaas.resource.creation.queue";

    @RabbitListener(queues = CREATION_QUEUE, admin = "amqpAdmin", autoStartup = "true")
    public void process(List<ApplicationParam> params) {
        try {
            if (ListTool.isEmpty(params)) {
                return;
            }
            for (ApplicationParam param : params) {
                JSONObject object = JSONTools.isJSONObj(JSONObject.toJSONString(param));
                logger.info("接收到资源申请创建请求：" + object.toJSONString());
                // 申请类别
                JSONObject configs = object.getJSONObject("configs");
                String category = configs.getString("category");
                // 当前申请类型是本服务需要处理的
                Result processResult = resourceOperationService.process(ResourceCategory.valueOf(category), object, OrderMessage.Operation.Application);
                logger.info("资源申请处理结果：{}", processResult.toString());
            }
        } catch (Exception e) {
            logger.error("Get error message:{}", e.getMessage());
        }
    }

}
