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

import com.alibaba.csp.sentinel.util.StringUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.exception.NacosException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;

import java.util.ArrayList;
import java.util.List;

/**
 * @author lfdc
 * @version 1.0
 * @className NacosConstants
 * @description 常量类
 * @company sckw
 * @date 2023-06-07 13:06:46
 */
public class NacosConstants {
    private static Logger logger = LoggerFactory.getLogger(NacosConstants.class);

    public static final String GROUP_ID = "SENTINEL_GROUP";

    /**
     * 流控规则后缀
     */
//    public static final String FLOW_DATA_ID_POSTFIX = "-sentinel-flow-rules";

    /**
     * 熔断规则后缀
     */
    public static final String DEGRADE_DATA_ID_POSTFIX = "-sentinel-degrade-rules";

    /**
     * 从Nacos server中查询响应规则，并将其反序列化成对应Rule实体
     *
     * @param configService nacos config service
     * @param groupId       组ID
     * @param dataId        Nacos DataId
     * @param clazz         类
     * @param <T>           泛型
     * @return 规则对象列表
     * @throws NacosException 异常
     */
    public static <T> List<T> getRuleEntitiesFromNacos(ConfigService configService,
                                                       String groupId, String dataId, Class<T> clazz) throws NacosException {
        String rules = configService.getConfig(dataId, groupId, 3000);

        logger.info("Pull Rule from Nacos Config : {}", rules);

        if (StringUtil.isEmpty(rules)) {
            return new ArrayList<>();
        }
        return JSON.parseArray(rules, clazz);
    }

    /**
     * 将规则序列化成为JSON信息，并发布到Nacos上
     *
     * @param <T>
     * @param configService
     * @param groupId
     * @param dataId
     * @param ruleEntities
     * @return
     * @throws NacosException
     */
    @Bean
    public static <T> Boolean setRuleEntitiesFromNacos(ConfigService configService,
                                                       String groupId, String dataId, List<T> ruleEntities) throws NacosException {
        String ruleEntitiesStr = JSON.toJSONString(ruleEntities);
        logger.info("Push Rule to Nacos Config : {}", ruleEntitiesStr);

        return configService.publishConfig(dataId, groupId, ruleEntitiesStr);
    }

}
