package com.tmerclub.cloud.common.cache.config;

import cn.hutool.core.util.StrUtil;
import com.tmerclub.cloud.common.cache.bo.AofRedisBO;
import com.tmerclub.cloud.common.exception.LuckException;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.redisson.config.SingleServerConfig;
import org.redisson.spring.data.connection.RedissonConnectionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;

/**
 * 多个redis管理
 * @author LGH
 */
@Component
@ConditionalOnProperty(value = "redis.aof.enable", havingValue = "true")
public class AofRedisConfig implements DisposableBean {

    private static final Logger LOGGER = LoggerFactory.getLogger(AofRedisConfig.class);

    private final StringRedisTemplate stringRedisTemplate;

    private final RedissonClient redissonClient;

    public AofRedisConfig(AofRedisBO aofRedisBO) {

        if (StrUtil.isBlank(aofRedisBO.getRedisAddr())) {
            throw new LuckException("请在yml配置好 aofRedis 的配置，见 com.tmerclub.cloud.common.cache.bo.AofRedisBO");
        }

        Config config = new Config();

        SingleServerConfig singleServerConfig = config.useSingleServer();
        if (StrUtil.isNotBlank(aofRedisBO.getPassword())) {
            singleServerConfig.setPassword(aofRedisBO.getPassword());
        }
        if (aofRedisBO.getDatabase() != null) {
            singleServerConfig.setDatabase(aofRedisBO.getDatabase());
        } else {
            singleServerConfig.setDatabase(0);
        }
        singleServerConfig.setAddress("redis://" + aofRedisBO.getRedisAddr());

        redissonClient = Redisson.create(config);
        LOGGER.info("创建redisson, redisson={}", redissonClient);

        stringRedisTemplate = new StringRedisTemplate();

        stringRedisTemplate.setValueSerializer(StringRedisSerializer.UTF_8);
        stringRedisTemplate.setKeySerializer(StringRedisSerializer.UTF_8);
        stringRedisTemplate.setConnectionFactory(new RedissonConnectionFactory(redissonClient));

        stringRedisTemplate.afterPropertiesSet();
    }


    public StringRedisTemplate getStringRedisTemplate() {
        return stringRedisTemplate;
    }


    @Override
    public void destroy() throws Exception {
        LOGGER.info("关闭redissonClient, redissonClient={}", redissonClient);
        redissonClient.shutdown();
    }
}
