package com.njcn.shiro.session;

import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.eis.AbstractSessionDAO;

import java.io.Serializable;
import java.util.Collection;

/**
 * @author hongawen
 * @date 2018/3/21 22:20
 */
public class UserShiroSessionDao extends AbstractSessionDAO {

    private UserShiroSessionRepository userShiroSessionRepository;

    /**
     * 创建sessionID，并将创建好的session保存进redis
     * @param session 当前会话
     */
    @Override
    protected Serializable doCreate(Session session) {
        Serializable sessionId = this.generateSessionId(session);
        this.assignSessionId(session, sessionId);
        userShiroSessionRepository.saveSession(session);
        return sessionId;
    }

    /**
     * 根据会话ID，获取会话
     * @param sessionID
     * @return  会话
     */
    @Override
    protected Session doReadSession(Serializable sessionID) {
        return userShiroSessionRepository.getSession(sessionID);
    }

    @Override
    public void update(Session session) throws UnknownSessionException {
        userShiroSessionRepository.saveSession(session);
    }

    @Override
    public void delete(Session session) {
        userShiroSessionRepository.deleteSession(session.getId());
    }

    @Override
    public Collection<Session> getActiveSessions() {
        return userShiroSessionRepository.getAllSessions();
    }

    public UserShiroSessionRepository getUserShiroSessionRepository() {
        return userShiroSessionRepository;
    }

    public void setUserShiroSessionRepository(UserShiroSessionRepository userShiroSessionRepository) {
        this.userShiroSessionRepository = userShiroSessionRepository;
    }
}
