package com.kxs.common.idempotent;

import cn.hutool.core.util.StrUtil;
import com.kxs.common.idempotent.aspect.IdempotentAspect;
import com.kxs.common.idempotent.config.RedisProperties;
import com.kxs.common.idempotent.expression.ExpressionResolver;
import com.kxs.common.idempotent.expression.KeyResolver;
import lombok.AllArgsConstructor;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author lengleng
 * @date 2020/9/25
 * <p>
 * 幂等插件初始化
 */
@AutoConfiguration
@Configuration(proxyBeanMethods = false)
@AutoConfigureAfter(RedisAutoConfiguration.class)
@EnableConfigurationProperties({ RedisProperties.class })
@AllArgsConstructor
public class IdempotentAutoConfiguration {

	private final RedisProperties redisProperties;

	/**
	 * 切面 拦截处理所有 @Idempotent
	 * @return Aspect
	 */
	@Bean
	public IdempotentAspect idempotentAspect() {
		return new IdempotentAspect();
	}

	/**
	 * key 解析器
	 * @return KeyResolver
	 */
	@Bean
	@ConditionalOnMissingBean(KeyResolver.class)
	public KeyResolver keyResolver() {
		return new ExpressionResolver();
	}

	@Bean
	@ConditionalOnMissingBean
	public RedissonClient redissonClient() {
		Config config = new Config();
		config.useSingleServer().setAddress(redisProperties.getPrefix() + redisProperties.getHost() + ":" + redisProperties.getPort());
		if(StrUtil.isNotBlank(redisProperties.getUsername())){
			config.useSingleServer().setUsername(redisProperties.getUsername());
		}
		if(StrUtil.isNotBlank(redisProperties.getPassword())){
			config.useSingleServer().setPassword(redisProperties.getPassword());
		}
		return Redisson.create(config);
	}

}
