package com.alibaba.csp.sentinel.dashboard.rule.nacos.degrade;

import com.alibaba.csp.sentinel.dashboard.datasource.entity.rule.DegradeRuleEntity;
import com.alibaba.csp.sentinel.dashboard.rule.DynamicRulePublisher;
import com.alibaba.csp.sentinel.dashboard.rule.nacos.NacosConfigProperties;
import com.alibaba.csp.sentinel.dashboard.rule.nacos.NacosConstants;
import com.alibaba.csp.sentinel.dashboard.rule.nacos.flow.FlowRuleNacosPublisher;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author lfdc
 * @version 1.0
 * @className DegradeRuleNacosPublisher
 * @description 熔断规则持久化到nacos
 * @company sckw
 * @date 2023-06-07 14:06:15
 */
//@Component("degradeRuleNacosPublisher")
@Service("degradeRuleNacosPublisher")
public class DegradeRuleNacosPublisher implements DynamicRulePublisher<List<DegradeRuleEntity>> {


    private static Logger logger = LoggerFactory.getLogger(FlowRuleNacosPublisher.class);
    @Autowired
    private NacosConfigProperties nacosConfigProperties;

    @Autowired
    private ConfigService configService;

    @Override
    public void publish(String appName, List<DegradeRuleEntity> rules) throws Exception {

        if(StringUtils.isBlank(appName)) {
            logger.error("传入的AppName为Null");
            return ;
        }
        if(null == rules) {
            logger.error("传入的熔断规则数据为null");
            return ;
        }
        logger.info("degradeDataId:"+appName);
        logger.info("degradeRulesList:"+rules);
        String dataId = new StringBuilder(appName).append(NacosConstants.DEGRADE_DATA_ID_POSTFIX).toString();
        NacosConstants.setRuleEntitiesFromNacos(configService, nacosConfigProperties.getGroupId(), dataId, rules);
    }

}
