/*
 * Copyright 1999-2018 Alibaba Group Holding Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.alibaba.csp.sentinel.dashboard.rule.nacos.flow;

import com.alibaba.csp.sentinel.dashboard.datasource.entity.rule.FlowRuleEntity;
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.NacosConfigUtil;
import com.alibaba.csp.sentinel.datasource.Converter;
import com.alibaba.csp.sentinel.util.AssertUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.exception.NacosException;
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.Component;

import java.util.List;


/**
 * @author lfdc
 * @version 1.0
 * @className NacosConfigProperties
 * @description 将通过Sentinel Dashboard上维护的流控规则数据持久化到Nacos中
 * @company sckw
 * @date 2023-06-07 10:06:18
 */
@Component("flowRuleNacosPublisher")
//@Service
public class FlowRuleNacosPublisher implements DynamicRulePublisher<List<FlowRuleEntity>> {
    /**
     * 将给定应用程序名称的规则发布到远程规则配置中心，也就是把你的规则写入到数据源
     * */
    private static Logger logger = LoggerFactory.getLogger(FlowRuleNacosPublisher.class);

    @Autowired
    private ConfigService configService;
    @Autowired
    private Converter<List<FlowRuleEntity>, String> converter;

    @Autowired
    private NacosConfigProperties nacosConfigProperties;

    @Override
    public void publish(String app, List<FlowRuleEntity> rules) throws Exception {
        AssertUtil.notEmpty(app, "app name cannot be empty");
        if (rules == null) {
            return;
        }
        configService.publishConfig(app + NacosConfigUtil.FLOW_DATA_ID_POSTFIX,
            NacosConfigUtil.GROUP_ID, converter.convert(rules));
        logger.info("flowDataId:"+app);
        logger.info("flowRulesList:"+rules);
        if(StringUtils.isBlank(app)) {
            logger.error("传入的AppName为Null");
            return ;
        }

        if(null == rules) {
            logger.error("传入的流控规则数据为null");
            return ;
        }
//        String dataId = new StringBuilder(app).append(NacosConstants.FLOW_DATA_ID_POSTFIX).toString();
////        NacosConstants.setRuleEntitiesFromNacos(configService, nacosConfigProperties.getGroupId(), dataId, rules);
//        setRuleEntitiesFromNacos(configService, nacosConfigProperties.getGroupId(), dataId, rules);
    }

    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);
    }
}
