package com.elab.redis.componts.config;

import com.elab.redis.componts.config.scope.RedisConfigRefreshCallback;
import com.elab.redis.config.props.ConfigRefreshProperties;
import com.elab.redis.config.ElabRedisProperties;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

public class ConfigCenterRedisStater {
    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private RedisConfigRefreshCallback refreshConfig;

    @Autowired
    private Environment environment;

    @Autowired
    private ElabRedisProperties redisProperties;

    @Autowired
    private RedisConnectionFactory redisConnectionFactory;

    @Autowired
    private RedisMessageListenerContainer messageListenerContainer;

    @PostConstruct
    public void init() {
        messageListenerContainer.setConnectionFactory(redisConnectionFactory);
        messageListenerContainer.addMessageListener(new RedisMsgListener(refreshConfig), topicList());
    }

    List<PatternTopic> topicList() {

        ConfigRefreshProperties configRefresh = redisProperties.getConfigRefresh();

        String pushKey = null;

        List<PatternTopic> topics = new ArrayList<>();

        if (configRefresh != null && StringUtils.isNotEmpty(configRefresh.getConfigPushCacheKey())) {
            pushKey = configRefresh.getConfigPushCacheKey();
        } else {
            String appName = environment.getProperty("spring.application.name", "unknown_application");
            String profile = environment.getProperty("spring.profiles.active", "");
            pushKey = appName + "-" + profile;
        }

        topics.add(new PatternTopic(pushKey + "*"));
        topics.add(new PatternTopic(pushKey.toLowerCase() + "*"));

        topics.forEach((topic) -> {
            String topic1 = topic.getTopic();
            logger.info("redis 关注的topic : " + topic1);
        });

        return topics;
    }

}
