package cn.com.qmth.stmms.common.session.service.impl;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.Cache.ValueWrapper;
import org.springframework.cache.CacheManager;

import cn.com.qmth.stmms.common.session.model.StmmsSession;
import cn.com.qmth.stmms.common.session.service.SessionService;

public class CacheSessionServiceImpl implements SessionService, InitializingBean {

    @Autowired
    private CacheManager cacheManager;

    private Cache cache;

    @Override
    public void afterPropertiesSet() throws Exception {
        cache = cacheManager.getCache("session_cache");
    }

    @Override
    public void put(HttpServletRequest request, HttpServletResponse response, StmmsSession ss) {
        if (ss.isInvalid()) {
            remove(request, response);
        } else {
            String sessionId = request.getSession().getId();
            cache.put(sessionId, ss);
        }
    }

    @Override
    public StmmsSession get(HttpServletRequest request) {
        String sessionId = request.getSession().getId();
        ValueWrapper wrapper = cache.get(sessionId);
        StmmsSession ss = null;
        if (wrapper != null && wrapper.get() != null && wrapper.get() instanceof StmmsSession) {
            ss = (StmmsSession) wrapper.get();
            if (!ss.getId().equals(sessionId)) {
                ss = null;
            }
        }
        if (ss == null) {
            ss = new StmmsSession();
            ss.setId(sessionId);
            cache.put(sessionId, ss);
        }
        return ss;
    }

    @Override
    public void remove(HttpServletRequest request, HttpServletResponse response) {
        String sessionId = request.getSession().getId();
        cache.evict(sessionId);
    }

}
