package me.chyxion.tigon.shiro;

import java.io.Serializable;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.cache.Cache;
import javax.annotation.PostConstruct;
import org.apache.shiro.cache.MapCache;
import org.apache.shiro.session.Session;
import me.chyxion.tigon.sequence.IdSequence;
import org.apache.shiro.cache.CacheException;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.shiro.cache.AbstractCacheManager;
import org.apache.shiro.session.mgt.eis.CachingSessionDAO;
import org.apache.shiro.session.mgt.eis.SessionIdGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO;

/**
 * @version 0.0.1
 * @since 0.0.1
 * @author Shaun Chyxion <br>
 * chyxion@163.com <br>
 * Sep 8, 2014 7:43:05 PM
 */
@Slf4j
public class SessionDAOSupport extends EnterpriseCacheSessionDAO {
    @Autowired(required = false)
    private Cache<Serializable, Session> sessionCache;
    @Autowired
    private IdSequence idSeq;

    /**
     * init session dao
     */
    @PostConstruct
    void init() {
        if (sessionCache == null) {
            log.info("No Custom Session Store Found, Use Map Cache.");
            sessionCache = new MapCache<Serializable, Session>(
                CachingSessionDAO.ACTIVE_SESSION_CACHE_NAME, 
                new ConcurrentHashMap<Serializable, Session>());
        }
        else {
            log.info("Use Custom Session Cache [{}].", sessionCache);
        }
        setCacheManager(new AbstractCacheManager() {
            /**
             * {@inheritDoc}
             */
            @Override
            protected Cache<Serializable, Session> createCache(String name) 
                throws CacheException {
                log.info("Create Session Cache [{}] Result [{}].", name, sessionCache);
                return sessionCache;
            }
        });
        setSessionIdGenerator(new SessionIdGenerator() {
            /**
             * {@inheritDoc}
             */
            @Override
            public Serializable generateId(Session session) {
                return idSeq.get();
            }
        });
    }
}
