package top.baogutang.common.config;

import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.refresh.ContextRefresher;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Properties;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;

/**
 * @description: nacos config listener
 * @author: nikooh
 * @date: 2024/07/02 : 18:37
 */
@Slf4j
@Component
public class NacosConfigExchangeListener {

    @Resource
    private ContextRefresher contextRefresher;

    @Value("${spring.cloud.nacos.config.server-addr}")
    private String serverAddr;

    @Value("${spring.application.name}")
    private String dataId;

    @Value("${spring.cloud.nacos.config.group}")
    private String group;

    @Value("${spring.cloud.nacos.config.namespace}")
    private String namespace;

    @PostConstruct
    public void addNacosConfigListener() throws NacosException {
        Properties properties = new Properties();
        properties.put(PropertyKeyConst.SERVER_ADDR, serverAddr);
        properties.put(PropertyKeyConst.NAMESPACE, namespace);
        ConfigService configService = NacosFactory.createConfigService(properties);
        configService.addListener(dataId, group, new Listener() {
            @Override
            public void receiveConfigInfo(String configInfo) {
                log.info(">>>>>>>>>>receive config change! dataId:{},group:{}<<<<<<<<<<", dataId, group);
                CompletableFuture.runAsync(() -> contextRefresher.refresh());
            }

            @Override
            public Executor getExecutor() {
                return null;
            }
        });
    }
}
