package cn.wisenergy.shiro.util.redis;

import cn.wisenergy.common.utils.exception.BASE_RESP_CODE_ENUM;
import cn.wisenergy.common.utils.exception.BaseCustomException;
import cn.wisenergy.shiro.util.ApplicationContextUtils;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.Collection;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @description:
 * @author: nh
 * @create: 2021-04-05 18:16
 **/
public class RedisCache<K,V> implements Cache<K,V> {

    //初始化Log日志
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private String cacheName;

    private static final long EXPIRE_TIME = 30 * 60;

    public RedisCache() {
    }

    public RedisCache(String cacheName) {
        this.cacheName = cacheName;
    }

    @Override
    public V get(K k) throws CacheException {
        Object o = getRedisUtil().opsForValue().get(this.cacheName + k.toString());
        return (V) o;
    }

    @Override
    public V put(K k, V v) throws CacheException {
        getRedisUtil().opsForValue().set(this.cacheName + k.toString(),v,EXPIRE_TIME, TimeUnit.SECONDS);
        return null;
    }

    @Override
    public V remove(K k) throws CacheException {
        logger.debug("从redis中删除 key [" + k + "]");
        try {
            V previous = get(k);
            getRedisUtil().delete(this.cacheName + k.toString());
            return previous;
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.RESOURCE_NOT_FOUND);
        }
    }

    @Override
    public void clear() throws CacheException {
    }

    @Override
    public int size() {
        return 0;
    }

    @Override
    public Set<K> keys() {
        return null;
    }

    @Override
    public Collection<V> values() {
        return null;
    }

    RedisTemplate getRedisUtil(){
        return (RedisTemplate) ApplicationContextUtils.getBean("redisTemplate");
    }

}
