package cc.smtweb.framework.core.cache.redis.config;


import cc.smtweb.framework.core.cache.redis.RedisManager;
import io.lettuce.core.RedisURI;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 〈redis配置〉
 *
 * @author kevin
 * @since 1.0.0
 */
@Configuration
public class RedisConfig {
    @Value("${spring.redis.name:127.0.0.1}")
    private String clientName;

    @Value("${spring.redis.host:127.0.0.1}")
    private String redisHost;

    @Value("${spring.redis.port:6379}")
    private int redisPort;

    @Value("${spring.redis.username:}")
    private String redisUserName;

    @Value("${spring.redis.password:}")
    private String redisPassword;

    @Value("${spring.redis.database:}")
    private String redisDb;

    @Autowired
    private ApplicationContext applicationContext;


    @Bean
    public RedisManager redisManager() {
        RedisURI redisUri = RedisURI.create(redisHost, redisPort);
        if (StringUtils.isNotBlank(clientName)) {
            redisUri.setClientName(clientName);
        }
        if (StringUtils.isNotBlank(redisDb)) {
            redisUri.setDatabase(Integer.parseInt(redisDb));
        }
        if (StringUtils.isNotBlank(redisUserName)) {
            redisUri.setUsername(redisUserName.trim());
        }
        if (StringUtils.isNotBlank(redisPassword)) {
            redisUri.setPassword((CharSequence) redisPassword.trim());
        }

        return new RedisManager(applicationContext, redisUri);
    }
}
