package com.izouma.nineth.config;

import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.data.redis.cache.RedisCache;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;

import java.time.Duration;
import java.util.Map;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 自定义缓存管理（自定义失效时间）
 */
public class CustomRedisCacheManager extends RedisCacheManager {

    private Pattern extractNumber = Pattern.compile("\\d+");


    public CustomRedisCacheManager(RedisCacheWriter cacheWriter, RedisCacheConfiguration defaultCacheConfiguration) {
        super(cacheWriter, defaultCacheConfiguration);
    }

    public CustomRedisCacheManager(RedisCacheWriter cacheWriter, RedisCacheConfiguration defaultCacheConfiguration,
                                   Map<String, RedisCacheConfiguration> initialCacheConfigurations) {
        super(cacheWriter, defaultCacheConfiguration, initialCacheConfigurations, true);
    }


    @Override
    protected RedisCache createRedisCache(String name, RedisCacheConfiguration cacheConfig) {
        String[] array = name.split("#");
        if (array.length > 1) {
            // 解析TTL
            String ttlValue = Objects.toString(array[1],"");
            Matcher matcher = extractNumber.matcher(ttlValue);
            if(matcher.find()){
                Long seconds = NumberUtils.toLong(matcher.group());
                if(seconds > 0){
                    cacheConfig = cacheConfig.entryTtl(Duration.ofSeconds(seconds)); // 秒
                }
            }

        }
        return super.createRedisCache(name, cacheConfig);
    }


}
