package cn.edu.whu.boot.user.services.impl;

import cn.edu.whu.boot.user.entities.User;
import cn.edu.whu.boot.user.services.SessionService;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.support.DefaultSubjectContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
public class SessionServiceImpl implements SessionService {

    private final SessionDAO sessionDAO;

    public SessionServiceImpl(SessionDAO sessionDAO) {
        this.sessionDAO = sessionDAO;
    }

    @Override
    public List<Session> getAllSessions() {
        return new ArrayList<>(sessionDAO.getActiveSessions());
    }

    @Override
    public Optional<Session> getSessionByUserId(int userId) {
        // 在当前所有会话中查找指定用户的会话
        return sessionDAO
                .getActiveSessions()
                .stream()
                .filter(session -> {
                    if (session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY) != null) {
                        SimplePrincipalCollection simplePrincipalCollection = (SimplePrincipalCollection)
                                session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
                        User user = (User) simplePrincipalCollection.getPrimaryPrincipal();
                        return user.getId() == userId;
                    } else {
                        return false;
                    }
                })
                .findFirst();
    }

    @Override
    public Optional<Session> getSessionByUsername(String username) {
        return sessionDAO
                .getActiveSessions()
                .stream()
                .filter(session -> {
                    if (session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY) != null) {
                        SimplePrincipalCollection simplePrincipalCollection = (SimplePrincipalCollection)
                                session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
                        User user = (User) simplePrincipalCollection.getPrimaryPrincipal();
                        return user.getUsername().equals(username);
                    } else {
                        return false;
                    }
                })
                .findFirst();
    }

    @Override
    public void forceLogout(String sessionId) {
        Session session = sessionDAO.readSession(sessionId);
        // 设置 session 过期
        // session 并不会立刻从 ActiveSessions 中剔除，
        // 需要通过 timeout 属性判断是否过期
        session.setTimeout(0);
    }
}
