package org.ssssssss.magicapi.redis;


import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.EnableAsync;
import org.ssssssss.magicapi.utils.Assert;

import java.util.LinkedHashMap;
import java.util.Map;


@Slf4j
@EnableAsync
@Configuration
@ConfigurationProperties(prefix = "magic-api.redis")
@Import({RedisInstanceFactory.class,MagicRedisConfiguration.class,})
public class MagicDynamicRedisAutoConfig implements InitializingBean {

    @Getter
    public static String primary;

    @Autowired
    public  RedisInstanceFactory redisInstanceFactory;

    @Getter
    private static Map<String, MagicRedisProperties> dynamic = new LinkedHashMap<>();

    @Override
    public void afterPropertiesSet() {
        Assert.isNotNull(primary, "Redis未设置默认库");
        dynamic.forEach((redisName, redisProperty) -> {
            redisInstanceFactory.buildRedisTemplate(redisName, redisProperty);
        });
        log.info("[动态Redis]--共创建Redis[{}]个", dynamic.size());
    }

    @Bean
    @ConditionalOnMissingBean
    public StringRedisTemplate stringRedisTemplate() {
        MagicRedisProperties redisProperties = dynamic.get(primary);
        RedisConnectionFactory connectionFactory = redisInstanceFactory.buildLettuceConnectionFactory(primary, redisProperties);
        StringRedisTemplate template = new StringRedisTemplate();
        template.setConnectionFactory(connectionFactory);
        return template;
    }

    @Bean
    @ConditionalOnMissingBean
    public RedisTemplate<Object, Object> redisTemplate() {
        MagicRedisProperties redisProperties = dynamic.get(primary);
        RedisConnectionFactory connectionFactory = redisInstanceFactory.buildLettuceConnectionFactory(primary, redisProperties);
        RedisTemplate<Object, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory);
        return template;
    }


    public void setPrimary(String primary) {
        MagicDynamicRedisAutoConfig.primary = primary;
    }

    public void setDynamic(Map<String, MagicRedisProperties> dynamic) {
        MagicDynamicRedisAutoConfig.dynamic = dynamic;
    }

    public static MagicRedisProperties getPrimaryRedisProp() {
        return dynamic.get(primary);
    }
}
