package cn.com.qmth.stmms.common.cache;

import java.util.Collection;
import java.util.LinkedList;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.Cache;
import org.springframework.cache.transaction.AbstractTransactionSupportingCacheManager;
import org.springframework.data.redis.core.RedisTemplate;

public class RedisCacheManager extends AbstractTransactionSupportingCacheManager {

    protected final Logger log = LoggerFactory.getLogger(RedisCacheManager.class);

    @SuppressWarnings("rawtypes")
    private RedisTemplate template;

    private long defaultExpiration = 0;

    public RedisCacheManager(RedisTemplate<? extends Object, ? extends Object> template) {
        this.template = template;
    }

    @Override
    public Cache getCache(String name) {
        Cache cache = super.getCache(name);
        if (cache == null) {
            return createAndAddCache(name);
        }
        return cache;
    }

    @Override
    protected Collection<? extends Cache> loadCaches() {
        Collection<Cache> result = new LinkedList<Cache>();
        for (String cacheName : getCacheNames()) {
            result.add(getCache(cacheName));
        }
        return result;
    }

    private Cache createAndAddCache(String cacheName) {
        addCache(createCache(cacheName));
        return super.getCache(cacheName);
    }

    @SuppressWarnings("unchecked")
    private RedisCache createCache(String cacheName) {
        return new RedisCache(cacheName, template, defaultExpiration);
    }

}
