package com.steerinfo.auth.shiro.cache;

import java.util.Collection;
import java.util.Set;

import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;
import org.apache.shiro.cache.CacheManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;

import com.steerinfo.framework.cache.Caches;

/**
 * 
 * @Title: CustomCacheManager.java
 * @Package com.steer.framework.auth.shiro.cache
 * @Description: TODO
 * @author 鄢利
 * @date 2018年7月16日
 * @Copyright © 2018湖南视拓信息技术股份有限公司. All rights reserved.
 */
public class CustomCacheManager implements CacheManager {

    @Autowired
    @Lazy
    Caches caches;

    @Override
    public Cache<Object, AuthorizationInfo> getCache(String name) throws CacheException {
        return new CacheWrapper(caches);
    }

    static class CacheWrapper implements Cache<Object, AuthorizationInfo> {
        private Caches caches;

        CacheWrapper(Caches caches) {
            this.caches = caches;
        }

        @Override
        public AuthorizationInfo get(Object key) throws CacheException {
            String k = key.hashCode() + key.toString();
            return (AuthorizationInfo)caches.getOneHourCache().get(k, AuthorizationInfo.class);
        }

        @Override
        public AuthorizationInfo put(Object key, AuthorizationInfo value) throws CacheException {
            String k = key.hashCode() + key.toString();
            caches.getOneHourCache().put(k, value);
            return value;
        }

        @Override
        public AuthorizationInfo remove(Object key) throws CacheException {
            String k = key.hashCode() + key.toString();
            caches.getOneHourCache().remove(k);
            return null;
        }

        @Override
        public void clear() throws CacheException {
            caches.getOneHourCache().cleanUp();
        }

        @Override
        public int size() {
            throw new UnsupportedOperationException("invoke spring cache abstract keys method not supported");
        }

        @Override
        public Set keys() {
            throw new UnsupportedOperationException("invoke spring cache abstract keys method not supported");
        }

        @Override
        public Collection values() {
            throw new UnsupportedOperationException("invoke spring cache abstract values method not supported");
        }
    }
}
