package cn.quant.baa.pay.config;

import com.github.benmanes.caffeine.cache.Caffeine;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.caffeine.CaffeineCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.TimeUnit;

/**
 * Created by Administrator on 2021/8/23 0023.
 */
@Configuration
@EnableCaching
public class LocalCacheConfiguration {

    public final static String LOCAL_CACHE_ACQUIRER = "LOCAL_CACHE_ACQUIRER";
    public final static String LOCAL_CACHE_PROFILE = "LOCAL_CACHE_PROFILE";
    public final static String LOCAL_CACHE_MANAGER = "localCacheManager";

    @Value("${quant.baapay.acquirer.local-cache-expire.time}")
    private Integer acquirerExpireTime;

    @Value("${quant.baapay.acquirer.local-cache-expire.unit}")
    private TimeUnit acquirerExpireUnit;

    @Value("${quant.baapay.acquirer.local-cache-expire.size}")
    private Integer acquirerExpireSize;

    @Value("${quant.baapay.profile.local-cache-expire.time}")
    private Integer profileExpireTime;

    @Value("${quant.baapay.profile.local-cache-expire.unit}")
    private TimeUnit profileExpireUnit;

    @Value("${quant.baapay.profile.local-cache-expire.size}")
    private Integer profileExpireSize;

    @Bean(value = LOCAL_CACHE_MANAGER)
    public CacheManager localCacheManager() {
        //TODO:reload cached data
        CaffeineCacheManager cacheManager = new CaffeineCacheManager();
        cacheManager.registerCustomCache(LOCAL_CACHE_ACQUIRER,
                Caffeine.newBuilder()
                        .expireAfterWrite(acquirerExpireTime, acquirerExpireUnit)
                        .maximumSize(acquirerExpireSize == null ? 500 : acquirerExpireSize)
                        .build());

        cacheManager.registerCustomCache(LOCAL_CACHE_PROFILE,
                Caffeine.newBuilder()
                        .expireAfterWrite(profileExpireTime, profileExpireUnit)
                        .maximumSize(profileExpireSize == null ? 500 : profileExpireSize)
                        .build());
        return cacheManager;
    }
}
