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.DynamicRuleProvider;
import com.alibaba.csp.sentinel.dashboard.rule.nacos.NacosConfigProperties;
import com.alibaba.csp.sentinel.dashboard.rule.nacos.NacosConstants;
import com.alibaba.nacos.api.config.ConfigService;
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 DegradeRuleNacosProvider
 * @description 熔断Provider 实现从Nacos配置中心获取熔断规则
 * @company sckw
 * @date 2023-06-07 13:06:50
 */

//@Component("degradeRuleNacosProvider")
@Service("degradeRuleNacosProvider")
public class DegradeRuleNacosProvider implements DynamicRuleProvider<List<DegradeRuleEntity>> {
    private static Logger logger=LoggerFactory.getLogger(DegradeRuleNacosProvider.class);

    @Autowired
    private NacosConfigProperties nacosConfigProperties;

    @Autowired
    private ConfigService configService;

//    @Autowired
//    private Converter<String, List<DegradeRuleEntity>> converter;

    //    @Override
//    public List<DegradeRuleEntity> getRules(String appName) throws Exception {
//
//        //定义dataId 应用名+固定后缀
//        String dataId = new StringBuilder(appName).append(NacosConstants.DEGRADE_DATA_ID_POSTFIX).toString();
//
//        List<DegradeRuleEntity> list = NacosConstants.getRuleEntitiesFromNacos(configService, nacosConfigProperties.getGroupId(), dataId, DegradeRuleEntity.class);
//
//        return list;
////        String rules = configService.getConfig(appName + NacosConfigUtil.DEGRADE_DATA_ID_POSTFIX,
////                NacosConfigUtil.GROUP_ID, 3000);
////        if (StringUtil.isEmpty(rules)) {
////            return new ArrayList<>();
////        }
////        return converter.convert(rules);
//    }
    @Override
    public List<DegradeRuleEntity> getRules(String appName) throws Exception {

        //定义dataId 应用名+固定后缀
        String dataId = new StringBuilder(appName).append(NacosConstants.DEGRADE_DATA_ID_POSTFIX).toString();

        List<DegradeRuleEntity> list = NacosConstants.getRuleEntitiesFromNacos(configService, nacosConfigProperties.getGroupId(), dataId, DegradeRuleEntity.class);

        logger.info("springApplicationName:"+appName);
        logger.info("degradeDataId:"+dataId);
        logger.info("degradeRulesList:"+list);
        return list;
    }
}
